Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路: 如果数组是无序的, 似乎没有什么好的办法,只能 逐层去遍历 ,时间复杂度 O(n^3) .
如果时间是有序的,可否用首尾指针呢 ? 但是三个数貌似不行。 可是我们可以把问题转化一下,转化为 2 个数 与 target -第三个数的问题 。 这样问题就成了 2 个数 和的问题。 时间复杂度 O(n^2) .
注意: 在查找所有组合时,需要判断重复的情况 , 如例子中的 1 -1 0 ,0 1 -1 等 。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &nums) {
vector<vector<int>> Res;
std::sort(nums.begin(),nums.end());
int target = 0; //auto match others scenario
for(int i = 0;i<nums.size();i++)
{
if(nums[i]> target)
break;
int front = i+1;
int back = nums.size()-1;
int subTarget = target - nums[i];
while(front < back)
{
int sum = nums[front]+nums[back];
if(sum > subTarget)
{
back--;
}
else if(sum < subTarget)
{
front++;
}
else
{
//Note : find all pair data that the sum is sum .
vector<int> subRes;
subRes.push_back(nums[i]);
subRes.push_back(nums[front]);
subRes.push_back(nums[back]);
Res.push_back(subRes);
//from front , skip dup value
while(front <back && nums[front]== subRes[1])
front++;
//from back , skip dup value
while(front <back && nums[back]== subRes[2])
back--;
}
}
//from the first ,skip dup value
while(i<nums.size()-1 && nums[i] == nums[i+1])
i++;
}
return Res;
}
};