题目:
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] ]
AC:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(nums);
if (null == nums || nums.length < 3 || nums[nums.length - 1] < 0) {
return result;
}
for (int x = 0; x < nums.length - 2 && nums[x] <= 0; x++) {
if (x == 0 || nums[x] != nums[x - 1]) {
int y = x + 1;
int z = nums.length - 1;
int target = -nums[x];
while (y < z) {
if (nums[y] + nums[z] == target) {
result.add(Arrays.asList(nums[x], nums[y], nums[z]));
y++;
z--;
while (y < z && nums[y] == nums[y - 1]) {
y++;
}
while (y < z && nums[z] == nums[z + 1]) {
z--;
}
}
else if (nums[y] + nums[z] < target) {
y++;
}
else {
z--;
}
}
}
}
return result;
}
}