Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:1
2
3
4Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:
假设每个输入都只有一个解决方案,先新建一个Map集合,先循环一遍nums数组,以target - nums[i]为key,以索引i为value,
放入Map中;然后再循环一遍nums数组,以nums[i]为key,取出v,如果v存在且不等与i,则代表找到了匹配值,返回唯一解int[]{i, v}。
Solution:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
m.put(target - nums[i], i);
}
for(int i = 0; i < nums.length; i++){
Integer v = m.get(nums[i]);
if(v != null && v != i){
return new int[]{i, v};
}
}
throw new RuntimeException();
}
}