15. 3Sum
Two sum的进阶

思路一

利用HashMap存储另外两个数字的和,然后遍历数组类似于Two sum的思路
但是3重循环,超时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length < 3) {
return new ArrayList<List<Integer>>();
}
Arrays.sort(nums);
Set<List<Integer>> res = new HashSet<List<Integer>>();
// 3层循环,o(n^3)超时
for (int k = 0; k < nums.length; k++) {
HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
for (int i = k + 1; i < nums.length; i++) {
if (i == k + 1 || nums[i] != nums[i - 1]) {
for (int j = i + 1; j < nums.length; j++) {
if (j == i + 1 || nums[j] != nums[j - 1]) {
int tmp = nums[i] + nums[j];
if (!map.containsKey(tmp)) {
map.put(tmp, new ArrayList<Integer>());
}
List<Integer> list = map.get(tmp);
list.add(nums[i]);
list.add(nums[j]);
}
}
}
}
//
if (map.containsKey(-nums[k])) {
List<Integer> tmp = map.get(-nums[k]);
for (int j = 0; j < tmp.size(); j += 2) {
List<Integer> list = new ArrayList<Integer>();
int s = Math.min(tmp.get(j), tmp.get(j + 1));
int b = tmp.get(j) == s ? tmp.get(j + 1) : tmp.get(j);
if (s > nums[k]) {
list.add(nums[k]);
list.add(s);
list.add(b);
} else {
list.add(s);
if (b > nums[k]) {
list.add(nums[k]);
list.add(b);
} else {
list.add(b);
list.add(nums[k]);
}
}
res.add(list);
}
}
}
return new ArrayList<List<Integer>>(res);
}

思路二

先排序,从头开始遍历,从剩余的数字中利用两指针找和是其相反数的的两个数字
这么做是因为数组有序,时间复杂度o(nnlogN)
加入队列判断重复是利用Set<List<Integer>>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> res = new HashSet<List<Integer>>();
for(int i = 0; i < nums.length; i++){
int low = i + 1;
int high = nums.length - 1;
while(low < high){
if(nums[low] + nums[high] < -nums[i]){
low++;
}else if(nums[low] + nums[high] > -nums[i]){
high--;
}else{
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[low]);
list.add(nums[high]);
res.add(list);
low++;
high--;
}
}
}
return new ArrayList<List<Integer>>(res);
}