问题内容是:给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引。

比如:给定​​nums = [2, 7, 11, 15], target = 9​​​ 那么要返回 ​​[0, 1]​​,因为​​2 + 7 = 9​

Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引_Test

 

这道题的优解是,一次遍历+HashMap:

先去Map中找需要的数字,没有就将当前的数字保存在Map中,如果找到需要的数字,则一起返回

Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引_i++_02

代码:

public int[] testTwoSum(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");
}


@Test
public void test4(){
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] j = testTwoSum(nums, target);
System.out.println(Arrays.toString(j));
}