题目描述:
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] ]
中文理解:
给出一个数和数列,找出数列中三个数和为该数的所有组合。
解题思路:
将数组排序,然后外层循环遍历一遍,内循环采用双指针start,end来进行遍历,若和为target则加入,当三个数和为target时,注意将收尾相同的数字过滤掉,不然会有重复的集合。
代码(java):
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res=new ArrayList();
if(nums.length<3)return res;
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1])continue;
int start=i+1,end=nums.length-1;
int target=0-nums[i];
while(start<end){
if(nums[start]+nums[end]<target)start++;
else if(nums[start]+nums[end]>target)end--;
else if(nums[start]+nums[end]==target){
List<Integer> element=new ArrayList();
element.add(nums[i]);
element.add(nums[start]);
element.add(nums[end]);
res.add(element);
while(start<end&& nums[start]==nums[start+1])start++;
start++;
while(start<end&& nums[end]==nums[end-1])end--;
end--;
}
}
}
return res;
}
}