Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
给定一个数组,求其3个元素和为0的所有集合。由于是二刷,第一想法居然是回溯法,递归找出所有3个元素的集合,然后选择符合条件的集合。回溯法用来解决复杂的,规模较大的问题很好使用,可以说是很多问题的通解。但是本题应该不需要这个略显笨重的算法,三数之和的问题可以由两数之和的问题推广而来,我们将数组排好序后,从左到右遍历数组,假设遍历到第i个元素,然后设置双指针,分别从第i+1和数组尾端进行夹逼。若三数之和大于0,右侧指针向左移;若三数之和小于0,左侧指针向右移。在这个过程中,我们需过滤掉重复的情况,共有三个位置,第一层遍历第i个元素、遍历左指针和右指针的时候。排序的算法复杂度为O(nlogn),找出符合的集合复杂度为O(n^2),故算法总的复杂度为O(n^2)。代码记录如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
sort(nums.begin(), nums.end());
int length = nums.size();
for(int i = 0; i < length; i++)
{
if(i > 0 && nums[i] == nums[i - 1])
continue;
int target = -nums[i];
int j = i + 1;
int k = length - 1;
while(j < k)
{
if(nums[j] + nums[k] == target)
{
ret.push_back({nums[i], nums[j], nums[k]});
j++;
k--;
while(j < k && nums[j] == nums[j - 1]) //nums[j] == nums[j - 1] not nums[j] == nums[j + 1]
j++;
while(j < k && nums[k] == nums[k + 1])
k--;
}
else if(nums[j] + nums[k] > target)
{
k--;
}
else
{
j++;
}
}
}
return ret;
}
};