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] ]
该题目的结果必须是不重复的,并且不难发现是升序排序,虽然不是特别难处理的点,但是要在处理这些问题时,使得代码优美整洁就不那么容易。
思路一:毫无技术含量的直男做法,穷竭搜索,O(N*3)
思路二:求出两个数相加的值,然后通过散列判断该和值的相反数是否在数组内。两个数值相加O(N*2),散列判断O(1)。而且还要加上升序排序,去重等操作。
思路三:先将数组进行排序,然后查看每个数的相反数是否为数组中两个元素的和。因为数组已经排完序,可以通过首尾两个指针来判断,时间复杂度为O(N)。这样做可以很方便的进行去重,升序排序。
代码如下:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(),nums.end());
int len = nums.size();
for(int k=0;k<len;k++)
{
int front=k+1,back=len-1;
int target = -nums[k];
while(front < back)
{
if(nums[front] + nums[back] < target)
{
front++;
}
else if(nums[front] + nums[back] > target)
{
back--;
}
else
{
vector<int> tmp(3,0);
tmp[0] = -target;
tmp[1] = nums[front];
tmp[2] = nums[back];
result.push_back(tmp);
while(front < back && nums[front] == tmp[1])
front++;
while(front < back && nums[back] == tmp[2])
back--;
}
}
while(k<len && nums[k+1] == nums[k])
k++;
}
return result;
}
};