3Sum
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: vector<vector<int>> twoSum(vector<int>& nums,int start,int target){ vector<vector<int>> ans; int i=start,j=nums.size()-1; while(i<j) { int sum=nums[i]+nums[j]; int left =nums[i],right = nums[j]; if(sum == target) { ans.push_back({left,right}); while(i<j && nums[i] == left) i++;//跳过重复的元素 while(i<j &&nums[j] == right) j--; } else if(sum<target) { while(i<j && nums[i] == left) i++; } else { while(i<j &&nums[j] == right) j--; } } return ans; } vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(),nums.end()); int n = nums.size(); vector<vector<int>> ans; for(int i=0;i<n;i++) { vector<vector<int>> tuples = twoSum(nums,i+1,-nums[i]);//找出符合的二元组 for(vector<int>& tuple :tuples) { tuple.push_back(nums[i]); ans.push_back(tuple); } // 跳过第一个数字重复的情况,否则会出现重复结果 while (i < n - 1 && nums[i] == nums[i + 1]) i++; } return ans; } };
注意:
1.双指针法,三个数的的合就先枚举每个数,然后再用双指针找另外两个数。
2.注意去重,连续相同的元素要及时跳过,在两个数的和时就要注意跳过。