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] ]
题解如下:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length < 3) {
return res;
}
//排序(这样那些相同的元素便都排在一起了,方便去重以及指针移动方向的判断)
Arrays.sort(nums);
//遍历,挑出第一个元素
for(int i= 0;i < nums.length - 2;i++) {
if(i==0 || (i > 0 && nums[i - 1] != nums[i])) {
int sum = 0 - nums[i];
//找剩下那两个元素
//定义两个指针,一个从头扫到尾,一个自尾扫到头
int low = i + 1,high = nums.length - 1;
while(low < high) {
//找到两个元素符合要求了
if(nums[low] + nums[high] == sum) {
res.add(Arrays.asList(nums[i],nums[low],nums[high]));
//去重操作
while(low < high && nums[low] == nums[low + 1]) {
low++;
}
while(low < high && nums[high] == nums[high -1]) {
high--;
}
low++;
high--;
}
//如果和小于sum,意味着目标值可能在low指针的右边
else if(nums[low] + nums[high] < sum) {
low++;
} else {
high--;
}
}
}
}
return res;
}
}