问题:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的两个下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
思路
首先遍历一次整数数组,将数组下标和值建立哈希表,再从头遍历一次哈希表,先得出当前读取的位置i上对于target的差complement,得到后通过查看该值是否保存在哈希表的value中,若存在,返回该值的key,否则读取下一元素。
技能点
1.java中HashMap结构知识点:
声明语句: Map<Integer, Integer> map = new HashMap<>();
添加内容: map.put(key,value);
鉴定存在: map.containsValues(value); //本例是把num[i]作为value
map.containsKey(key);
找到下标: map.get(value); //根据value返回下标
返回数组: return new int[]{num1,num2};
最终代码:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
//建立hashmap
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
//在哈希表中遍历每个元素,找到可能与之匹配成target的下标
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsValues(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}