给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。
时间: 2023-11-16 17:52:26 浏览: 50
给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。为了解决这个问题,你可以使用哈希表来存储数组中的元素及其索引。遍历数组,对于每个元素nums[i],判断target-nums[i]是否存在于哈希表中。如果存在,则说明找到了目标值,返回两个元素的索引;如果不存在,则将当前元素及其索引添加到哈希表中。下面是具体的代码实现:
```
private static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
int[] index = new int[2];
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(target - nums[i])) {
index[0] = hashMap.get(target - nums[i]);
index[1] = i;
break;
} else {
hashMap.put(nums[i], i);
}
}
return index;
}
```
相关问题
jsp写 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那
这个问题可以用暴力枚举、哈希表和双指针等方法解决。其中,哈希表和双指针的时间复杂度都是O(n),而暴力枚举的时间复杂度是O(n^2)。以下是双指针的解法:
首先将数组排序,然后使用双指针i,j分别从数组两端开始向中间靠拢。如果nums[i] + nums[j] > target,则j--;如果nums[i] + nums[j] < target,则i++;如果nums[i] + nums[j] == target,则找到了一组解。
Java代码如下:
```java
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Arrays.sort(nums);
int i = 0, j = nums.length - 1;
while (i < j) {
int sum = nums[i] + nums[j];
if (sum > target) {
j--;
} else if (sum < target) {
i++;
} else {
result[0] = i;
result[1] = j;
break;
}
}
return result;
}
```
C语言给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数设计思路
为了找到和为目标值的两个整数,我们可以使用哈希表来存储数组中的元素及其下标。具体步骤如下:
1. 创建一个哈希表,用于存储数组中的元素及其下标。
2. 遍历数组中的每个元素,对于每个元素,计算目标值与该元素的差值。
3. 在哈希表中查找该差值,如果存在,则返回该差值的下标和当前元素的下标。
4. 如果不存在,则将当前元素及其下标存入哈希表中。
C语言代码如下(假设数组中没有重复元素):
```c
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int* result = (int*)malloc(2 * sizeof(int)); *returnSize = 2;
int hashTable[100000] = {0}; // 哈希表,用于存储数组中的元素及其下标
for(int i = 0; i < numsSize; i++){
int complement = target - nums[i]; // 计算目标值与当前元素的差值
if(hashTable[complement] != 0){ // 在哈希表中查找差值
result[0] = hashTable[complement] - 1; // 返回差值的下标和当前元素的下标
result[1] = i;
return result;
}
hashTable[nums[i]] = i + 1; // 将当前元素及其下标存入哈希表中
}
return result;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)