-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0015. 3Sum
More file actions
35 lines (34 loc) · 1.07 KB
/
Copy path0015. 3Sum
File metadata and controls
35 lines (34 loc) · 1.07 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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i <= n - 3; i++) {
int sum = -nums[i];
int l = i + 1, r = n - 1;
while (l < r) {
if (nums[l] + nums[r] < sum) {
l++;
}
else if (nums[l] + nums[r] > sum) {
r--;
}
else {
res.add(Arrays.asList(nums[i], nums[l], nums[r]));
while (l + 1 < r && nums[l] == nums[l + 1]) {
l++;
}
l++;
while (l < r - 1 && nums[r] == nums[r - 1]) {
r--;
}
r--;
}
}
while (i + 1 <= n - 3 && nums[i + 1] == nums[i]) {
i++;
}
}
return res;
}
}