//一遍hash表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
题解过程:
[11, 2, 7, 15] target = 9
i = 0, Hashmap为空 => 不存在 => [entry[key=11,value=0]]
i = 1, Hashmap无7 => 不存在 => [entry[key=11,value=0], entry[key=2,value=1]]
i = 2, Hashmap有2 => 存在 => 返回 [1, 2]
[11, 2, 2, 15] target = 4
i = 0, Hashmap为空 => 不存在 => [entry[key=11,value=0]]
i = 1, Hashmap无2 => 不存在 => [entry[key=11,value=0], entry[key=2,value=1]]
i = 2, Hashmap有2 => 存在 => 返回 [1, 2]
时间复杂度 O(n)
空间复杂度 O(n)
//暴力法
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] == target - nums[j]){
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
题解过程:
[2, 11, 7, 15] target = 9
i = 0, j = 1 => 2 + 11 != 9
i = 0, j = 2 => 2 + 7 == 9 返回 [0, 1]
时间复杂度 O(n2)
空间复杂度 O(n)
//两遍hash表
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
题解过程:
[11, 2, 7, 15] target = 9
=> [entry[key=11,value=0],entry[key=2,value=1], entry[key=7,value=2], entry[key=15,value=3]] 存的顺序和Hashcode函数有关
i = 0, complement = -2 => map中不存在-2
i = 1, complement = 7 => map中存在2,且1 != 2 返回 [1, 2]
[11, 2, 2, 15] target = 4
=> [entry[key=11,value=0],entry[key=2,value=1, next] --> entry[key=2,value=2], , entry[key=15,value=3]]
i = 0, complement = -7 => map中不存在-7
i = 1, complement = 2 => map中存在2,且1 = 1 不符合,则 next 得 1 != 2 返回 [1, 2]
时间复杂度 O(n)
空间复杂度 O(n)
HashMap实现原理及源码分析 - dreamcatcher-cx - 博客园 https://www.cnblogs.com/chengxiao/p/6059914.html#t2