Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
SourceCode:
s1
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
//笔者提交版本;耗时:67ms;
publicclassSolution{
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int len = nums.length;
if(len < 3){return result;}
Set<ArrayList<Integer>> resultSet = new HashSet<>();
Arrays.sort(nums);
for(int i = 0;i<len-2;i++){
for(int j = i+1;j<len-1;j++){
int target = 0 - nums[i] - nums[j];
if(target < 0){
break;
}
int k = Arrays.binarySearch(nums,j+1,len,target);
if(0 <= k){
ArrayList<Integer> tmpArray = new ArrayList<Integer>();
tmpArray.add(nums[i]);
tmpArray.add(nums[j]);
tmpArray.add(nums[k]);
resultSet.add(tmpArray);
}
}
}
for(List<Integer> elem :resultSet){
result.add(elem);
}
return result;
}
}
s2
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
60
61
62
63
64
65
//该版本参考了Discuss,重新整理优化;耗时:8ms;
publicclassSolution{
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(len < 3){
return result;
}
//经过排序后,数据分为 负数区,0区,和正数区;
Arrays.sort(nums);
for(int i = 0, jLoc = len -1 , iLoc = len - 2; i < iLoc ; i++){