问题描述
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]
]
解题思路
该题最容易想到的算法就是对于数组中a,b,c全都分别遍历,找到a+b+c=0,但是该算法复杂度O(n3)太高。思考后发现3数之和等于0,必定有正有负,所以可以先对数组中数进行排序,然后i = 0, j = i + 1往后遍历,到倒数第三个数停止,排序后复杂度可以控制在O(n2)
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& sum) {
vector<vector<int>> result;
sort(sum.begin(), sum.end());
if (!sum.empty() && sum.back() < 0)
return {};
for (int k = 0; k < sum.size(); k++) {
if (sum[k] > 0)
break;
if (k > 0 && sum[k] == sum[k - 1])
continue;
int target = 0 - sum[k];
int i = k + 1, j = sum.size() - 1;
while (i < j) {
if (sum[i] + sum[j] == target) {
result.push_back({sum[k], sum[i], sum[j]});
while (i < j && sum[i] == sum[i + 1])
i++;
while (i < j && sum[j] == sum[j - 1])
j--;
i++;
j--;
}
else if (sum[i] + sum[j] < target)
i++;
else
j--;
}
}
return result;
}
};