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] ]
思路:暴力破解,其实我们都想到,但是这样面临着两个问题,首先是时间复杂度的问题,然后3个for循环还可能会导致重复选取的问题。
解题思路是:可以把它转化为 a+b =-c的问题。选取数组的其中一个数,对其添加负号。看是否满足存在两个数相加刚好等于它的负数。
class Solution {
public:
vector<vector<int>> threeSum(vector<int> &nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end()); //先对其进行排序,缩短寻找的时间复杂度。
for (int i = 0; i < nums.size(); i++) {
int target = -nums[i];
int front = i + 1;
int back = nums.size() - 1;
//如果target小于0,意味着nums[i]为正,而nums[front]和nums[back]都会大于它,所以不存在的
if (target < 0) {
break;
}
while (front < back) {
int sum = nums[front] + nums[back];
if (sum < target) front++;
else if (sum > target) back--;
else {
vector<int> arry(3, 0);
arry[0] = nums[i];
arry[1] = nums[front];
arry[2] = nums[back];
res.push_back(arry);
while (front < back &&nums[front] == arry[1]) front++;
while (front < back &&nums[back] == arry[2]) back--;
}
}
//筛除相等的数
while (i + 1 < nums.size() && nums[i + 1] == nums[i])
i++;
}
return res;
}
};
当然还有KSum问题,我们稍后再讨论