Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]]
Hide Company Tags
Amazon Microsoft Bloomberg Facebook Adobe Works Applications
Hide Tags
Array Two Pointers
Hide Similar Problems
(E) Two Sum (M) 3Sum Closest (M) 4Sum (M) 3Sum Smaller
/*思路: The idea is to sort an input array and then run through all indices of a possible first element of a triplet. For each possible first element we make a standard bi-directional 2Sum sweep of the remaining part of the array.
Also we want to skip equal elements to avoid duplicates in the answer without making a set or smth like that.
*/
// https://discuss.leetcode.com/topic/8125/concise-o-n-2-java-solution/8
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length -2 ; i++) {
if (i == 0 || ( i > 0 && nums[i] != nums[i-1])) {
int start = i + 1, end = nums.length - 1, sum = 0 - nums[i];
while (start < end) {
if (sum == nums[start] + nums[end]) {
res.add(Arrays.asList(nums[i], nums[start], nums[end]));
while (start < end && nums[start] == nums[start+1]) start++;
while (start < end && nums[end] == nums[end -1]) end--;
start++;
end--;
} else if (nums[start] + nums[end] < sum) {
// improve: skip duplicates
while (start < end && nums[start] == nums[start+1]) start++;
start++;
} else {
// improve: skip duplicates
while (start < end && nums[end] == nums[end -1]) end--;
end--;
}
}
}
}
return res;
}