forked from mdabarik/blind-75-leetcode-questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09--three-sum.java
31 lines (30 loc) · 1.26 KB
/
09--three-sum.java
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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> triplets = new ArrayList<>();
for (int i = 0; i <= nums.length - 3; i++) {
if (i == 0 || nums[i] != nums[i - 1]) {
int left = i + 1, right = nums.length - 1;
int target = 0 - nums[i];
while (left < right) {
if (nums[left] + nums[right] == target) {
List<Integer> triplet = new ArrayList<>();
triplet.add(nums[i]);
triplet.add(nums[left]);
triplet.add(nums[right]);
triplets.add(triplet);
while (left < nums.length - 1 && nums[left] == nums[left + 1]) left++;
while (right > 0 && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
}
}
return triplets;
}
} // TC: O(n log n) + O(n^2), SC: O(1)