用java实现下题:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案
时间: 2023-10-26 13:31:41 浏览: 17
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
相关问题
请使用Java代码实现:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
```java
import java.util.HashMap;
public class Solution {
public int[] twoSum(int[] nums, int target) {
// 创建一个HashMap,用于存储数组中的元素和它们的下标
HashMap<Integer, Integer> map = new HashMap<>();
// 遍历数组
for (int i = 0; i < nums.length; i++) {
// 计算目标值与当前元素的差值
int complement = target - nums[i];
// 在HashMap中查找差值是否存在
if (map.containsKey(complement)) {
// 如果存在,则返回差值的下标和当前元素的下标
return new int[] { map.get(complement), i };
}
// 如果差值不存在,则将当前元素和它的下标放入HashMap中
map.put(nums[i], i);
}
// 如果没找到,则返回空数组
return new int[] {};
}
}
```
以上代码使用了HashMap来存储数组中的元素和它们的下标,然后遍历数组,对于每个元素,计算目标值与它的差值,然后在HashMap中查找是否存在这个差值,如果存在,则返回差值的下标和当前元素的下标,否则将当前元素和它的下标放入HashMap中。如果遍历完整个数组都没有找到符合条件的两个元素,则返回空数组。
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;
}
```
相关推荐
![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)
![](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)