-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum.java
More file actions
58 lines (49 loc) · 1.57 KB
/
Copy pathThreeSum.java
File metadata and controls
58 lines (49 loc) · 1.57 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
package threeSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
List result = new ArrayList();
final int size = nums.length;
if (size <= 2) {
return result;
}
Arrays.sort(nums);
for (int i = 0; i < size; i++) {
if (i != 0 && nums[i] == nums[i-1])
continue;
int j = i + 1;
int k = size - 1;
while (j < k) {
if (nums[i] + nums[j] + nums[k] == 0) {
List<Integer> sums = new ArrayList<Integer>();
sums.add(nums[i]);
sums.add(nums[j]);
sums.add(nums[k]);
result.add(sums);
j++;
while (j < size && nums[j] == nums[j-1]) {
j++;
}
} else if (nums[i] + nums[j] + nums[k] < 0) {
j++;
} else if (nums[i] + nums[j] + nums[k] > 0) {
k--;
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {0,0, 0};
ThreeSum threeSum = new ThreeSum();
List<List<Integer>> result = threeSum.threeSum(nums);
for (List<Integer> list : result) {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + ", ");
}
System.out.println();
}
}
}