-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSum3.java
More file actions
29 lines (28 loc) · 880 Bytes
/
Copy pathSum3.java
File metadata and controls
29 lines (28 loc) · 880 Bytes
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Sum3 {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums.length < 3) {
return result;
}
Arrays.sort(nums);
int leftPos = 0;
while (leftPos < nums.length - 2) {
int leftInd = leftPos + 1;
int rightInd = nums.length - 1;
while (leftInd < rightInd) {
int sum = nums[leftPos] + nums[leftInd] + nums[rightInd];
if (sum == 0)
result.add(Arrays.asList(nums[leftPos], nums[leftInd], nums[rightInd]));
if (sum <= 0)
while(nums[leftInd] == nums[++leftInd] && leftInd < rightInd);
if (sum >= 0)
while(nums[rightInd] == nums[--rightInd] && leftInd < rightInd);
}
while(nums[leftPos] == nums[++leftPos] && leftPos < nums.length - 2);
}
return result;
}
}