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]
]Time: O(N^2)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
if nums is None:
return res nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
target = -nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[right] == target:
lst = [nums[i], nums[left], nums[right]]
res.append(lst)
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
return res
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// skip i as well
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
int j = i + 1, k = nums.length - 1;
// j and k cannot meet since may add the same number twice
while (j < k) {
int target = nums[i] + nums[j] + nums[k];
if (target == 0) {
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
j += 1;
while (j < k && nums[j] == nums[j - 1]) {
j += 1;
}
} else if (target < 0) {
j += 1;
} else {
k -= 1;
}
}
}
return res;
}
}