题目链接: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)
思路:一种直接的方法是三重循环, 每次枚举一个值, 需要注意的重复的值, 也就是当在这一层使用了一个值之后, 继续在这一层选值的时候不可以再选这个, 也就是跳过. 另外初始的时候是无序的, 因此需要对数组先排序. 其时间复杂度是O(n^3). 但是我们可以优化到O(n^2), 用双指针计数, 也就是先枚举一个值, 剩下的问题就退化成了2 sum的问题.
代码如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if(nums.size() < 3) return {};
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
int len = nums.size();
for(int i = 0; i < len-2; i++)
{
int left = i+1, right = len-1;
while(left < right)
{
int val = nums[i] + nums[left] + nums[right];
if(val ==0)
{
ans.push_back( vector<int>{nums[i], nums[left], nums[right]} );
while(left < right && nums[left]==nums[left+1]) left++;
left++, right--;
}
else if(val > 0) right--;
else left++;
}
while(i < len-1 && nums[i]==nums[i+1]) i++;
}
return ans;
}
};