我需要一个算两数之和的java代码,给定一个整数数组nums 和一个整数目标值target ,请你在该数组中找出和为目标值target 的那两个整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
时间: 2023-10-20 07:10:37 浏览: 18
好的,下面是一个简单的算法实现:
```java
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
result[0] = map.get(complement);
result[1] = i;
break;
}
map.put(nums[i], i);
}
return result;
}
```
这个算法使用了哈希表来存储数组中的值和它们对应的下标,然后遍历数组,对于每个数,检查是否存在一个与之配对的数,使得它们的和等于目标值。如果存在这样的一对数,就返回它们的下标。如果没有找到,则将当前数和它的下标存储到哈希表中,以便后续检查。
相关问题
给定一个整数数组nums和一个整数目标值terget
给定一个整数数组 nums 和一个整数目标值 target,你可以使用两种方法来找出和为目标值 target 的两个整数的数组下标。
第一种方法是使用两个for循环来遍历数组中的每个元素,然后查找是否存在一个值与 target-num 的元素。如果存在,就返回它们的数组下标。这种方法被称为暴力法,因为它尝试所有可能的组合。,并在哈希表中查找是否存在这个差值。如果存在,就返回当前元素的索引和差值的索引。这种方法的时间复杂度是O(n),因为哈希表的查找操作是常数时间复杂度。
给定整数数组nums和一个目标值target 在数组中找出和为目标值的两个整数 返回数组下标java
思路:使用哈希表存储已经遍历过的数字,遍历数组nums,对于每个数字num,查找是否存在另一个数字target-num在哈希表中,如果存在,返回两个数字的下标。
Java代码实现:
class Solution {
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");
}
}
相关推荐
![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)