题目分析
- 暴力法枚举每一对相加之和,时间复杂度:O(n2)
- 要求O(n),即扫描到一个就能花O(1)时间找到另一个加数,即用哈希表
- HashMap的key为数,value为下标,如果找到即返回,找不到,就把自己加进去作为另一个加数
Solution
public int[] twoSum(int[] nums, int target) {
if (nums == null) return null;
// 用来存放之前扫描过的元素
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer idx = map.get(target - nums[i]);
if (idx != null) return new int[]{idx, i};
map.put(nums[i], i);
}
return null;
}
Reference:小码哥MJ