https://leetcode-cn.com/problems/two-sum/
思路
有两种方式
- 双层遍历, 时间复杂度 O (n^2)
- 使用 map 存储, key 是元素, value 是索引. 时间复杂度 O (n)
/*
思路
O(n)
map.containsKey key 放 num , value 索引
其他解法: 双层循环 O(n^2)
*/
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int key = target - nums[i];
if (map.containsKey(key)) {
return new int[]{i, map.get(key)};
}
map.put(nums[i], i);
}
return new int[0];
}