題目描述
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]
]
思路
給定一個整型數組S,找到所有三個元素加起來為零的數。
思路1.
三個數加起來得是0,那么查找 0 - 前兩個數之和 是否在數組S里,在就說明S里這三個數相加是0.
那么就插入二維數組中。
排重:新得到的數要和已經在二維數組里的數比較,不相同才可以插入到二維數組。發現超時。
思路2.
首先排序數組S,利用雙指針一個在前,一個在后去比較加起來是否為零,然后雙指針繼續移動。
代碼
class Solution {
public:
vector< vector<int> > threeSum(vector<int>& nums) {
int i, j, k;
vector< vector<int> > res;
if(nums.size() <= 2)
return res;
sort(nums.begin(),nums.end());//排序從小到大
for(i = 0; i < nums.size() - 2; i++)
{
j = i+1;
k = nums.size() - 1;
while(j < k)
{
vector<int> initial;
if(nums[i] + nums[j] + nums[k] == 0)
{
initial.push_back(nums[i]);
initial.push_back(nums[j]);
initial.push_back(nums[k]);
res.push_back(initial);
++j;
--k;
while(j < k && nums[j-1] == nums[j])//向后移動了的值與之前相同
{
j++;
}
while(j < k && nums[k] == nums[k+1])
{
k--;
}
}
else if(nums[i] + nums[j] + nums[k] >= 0) //說明太大要縮小
{
k--;
}
else
j++;
}
while(i < nums.size() - 1 && nums[i] == nums[i+1])
{
i++;
}
}
return res;
}
};