题目:
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]
]
解析:题目是求3sum,我的解法是先将数组进行排序。然后取出一个数这样只要在剩余的数组里找到两个数之和为target-num[i]就行,这样3sum问题就变成了2sum问题,这个时候因为数组是有序的,所以使用two-pointers就可以解决。时间复杂度为O(N^2).
代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int> >vec;
if(nums.size()==0) return vec;
sort(nums.begin(),nums.end());
int size = nums.size();
int l,r;
for(int i=0;i<size;i++)
{
if(i>0&&nums[i]==nums[i-1]) continue;
int ans = -nums[i];
l = i+1;
r = size-1;
while(l<r)
{
int _2sum = nums[l]+nums[r];
if(_2sum>ans) r--;
else if(_2sum<ans) l++;
else
{
vector<int>temp;
temp.push_back(nums[i]);
temp.push_back(nums[l]);
temp.push_back(nums[r]);
vec.push_back(temp);
l++;
}
}
}
vec.erase(unique(vec.begin(),vec.end()),vec.end());
return vec;
}
};