15 3Sum
链接:https://leetcode.com/problems/3sum/
问题描述:
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
Hide Tags Array Two Pointers
Hide Similar Problems (M) Two Sum (M) 3Sum Closest (M) 4Sum
给出数组,求数组中所有三个数的和为0的组合。思路是这样的:
1 将数组排序。
2 从前往后取数字。取玩一个数字后,初始化两个‘指针’,p1指向之后的一个数字,p2指向最后一个数字。
3 求和如果等于0,则记录结果。如果大于0则p2–。如果小于0则p1++。
4 利用一些条件可以加速,否则容易通不过。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int p1,p2;
sort(nums.begin(),nums.end());
for(int i=0;i<(int)nums.size()-2;i++)
{
if(i > 0 && nums[i]==nums[i-1])
continue;
else if(nums[i]>0)
break;
p1=i+1;
p2=nums.size()-1;
while(p1<p2)
{
if(p1>i+1&&nums[p1]==nums[p1-1])
{
p1++;
continue;
}
else if(p2<nums.size()-1&& nums[p2]==nums[p2+1])
{
p2--;
continue;
}
else if(nums[i]+nums[p1]>0)
break;
else if(nums[i]+nums[p1]+nums[p2]==0)
{
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[p1]);
temp.push_back(nums[p2]);
result.push_back(temp);
p1++;
}
else if(nums[i]+nums[p1]+nums[p2]<0)
p1++;
else
p2--;
}
}
return result;
}
};