Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
- Beats 59% submissions
- Check duplicate when moving pointers, keep going when element is same with previous one.
- Carefully run through cases: [0, 0, 0], [0, 0, 0, 0] to make sure correctness
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for (int i=0; i<nums.length-2; i++) {
while (i > 0 && i < nums.length - 2 && nums[i] == nums[i-1]) {
i ++;
}
int l = i + 1, r = nums.length - 1;
while (l < r) {
if (nums[l] + nums[r] > - nums[i]) {
r --;
while (r >= 0 && nums[r+1] == nums[r]) {
r --;
}
}
else if (nums[l] + nums[r] < - nums[i]) {
l ++;
while (l < nums.length && nums[l-1] == nums[l]) {
l ++;
}
}
else {
Integer[] sum = {nums[i], nums[l], nums[r]};
res.add(Arrays.asList(sum));
r --; l ++;
while (r >= 0 && nums[r+1] == nums[r]) {
r --;
}
while (l < nums.length && nums[l-1] == nums[l]) {
l ++;
}
}
}
}
return res;
}
}
网友评论