思路
哈希复杂度为O(1),遍历数组,判断每次map中是否存在差值
示例
/**
* map 取值相加
* 复杂度O(1)
*/
private static int[] twoNumAdd_map(int[] nums, int target) {
HashMap<Integer, Integer> cap = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int other = target - num;
if (cap.containsKey(other)) {
return new int[]{cap.get(other), i};
}
cap.put(num, i);
}
throw new IllegalArgumentException("no result!");
}