forked from LjyYano/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL015_3Sum.java
More file actions
60 lines (42 loc) · 1.05 KB
/
L015_3Sum.java
File metadata and controls
60 lines (42 loc) · 1.05 KB
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
package LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class L015_3Sum {
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length < 3) {
return new ArrayList<List<Integer>>();
}
Set<List<Integer>> set = new HashSet<List<Integer>>();
Arrays.sort(nums);
for (int start = 0; start < nums.length; start++) {
if (start != 0 && nums[start - 1] == nums[start]) {
continue;
}
int mid = start + 1, end = nums.length - 1;
while (mid < end) {
int sum = nums[start] + nums[mid] + nums[end];
if (sum == 0) {
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[start]);
tmp.add(nums[mid]);
tmp.add(nums[end]);
set.add(tmp);
while (++mid < end && nums[mid - 1] == nums[mid])
;
while (--end > mid && nums[end + 1] == nums[end])
;
}
else if (sum < 0) {
mid++;
}
else {
end--;
}
}
}
return new ArrayList<List<Integer>>(set);
}
}