题目:
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] ]
思路:
对于3Sum而言,即使原数组是排好序的,也需要至少O(n^2)的时间复杂度。而排序的时间复杂度是O(nlogn),不影响最终的时间复杂度,所以我们可以首先对数组进行排序,然后采用双指针扫描的方法实现第二层循环。整个算法的时间复杂度就是O(n^2),空间复杂度为O(1)。
为了防止出现重复结果,需要注意一旦相邻元素相同,则后续元素应该跳过。详见下面代码的注释部分。另外一种简单方法是,将nums转存到一个set<int>中,然后在set<int>中完成两遍扫描。这样做的好处在于set不仅可以自动排序,而且可以自动去重。
代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> ret;
if(nums.size() < 3)
return ret;
sort(nums.begin(), nums.end());
long previous = LONG_MAX; // make sure previous is not equal to any element
for(int i = 0; i < nums.size() - 2; ++i)
{
int target = - nums[i];
if(target == previous) // make sure the first element is not duplicate
continue;
int j = i + 1;
int k = nums.size() - 1;
while(j < k)
{
if(nums[j] + nums[k] == target)
{
ret.push_back(vector<int>{nums[i], nums[j], nums[k]});
while(j < k && nums[j] == nums[j+1]) // make sure the second element is not duplicate
j++;
while(j < k && nums[k] == nums[k-1]) // make sure the third element is not duplicate
k--;
j++;
k--;
}
else if(nums[j] + nums[k] < target)
{
j++;
}
else
{
k--;
}
}
previous = target;
}
return ret;
}
};