题目
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.
Example:
given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[ [-1, 0, 1], [-1, -1, 2] ]
解法
直接穷举所有可能的时间复杂度为O(N^3),可以考虑穷举a的所有可能,计算b+c=-a,这样就转化成了LeetCode 1,两数相加等于指定数也可以使用数组排序后从首尾开始移动计算和的方法来解决。
所以该题的算法为:
首先对nums进行升序排列,用for循环枚举第一个数字a,下标记为i,b的下标为start=i+1, end=nums.size()-1,sum = nums[i] + nums[start] + nums[end]。
若sum = 0,则得到一组解;
若sum < 0,说明需要增大值,则start++;
若sum > 0, 说明需要减小值,则end–;
这里需要注意跳过重复的值,避免产生重复的解。
该方法时间复杂度为:O(N^2)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if (nums.size() < 3)
return result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
while (i > 0 && i < nums.size() && nums[i] == nums[i - 1])
i++;
int start = i + 1, end = nums.size() - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (sum < 0) {
start++;
while (start < end && nums[start] == nums[start - 1])
start++;
} else if (sum == 0) {
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[start]);
tmp.push_back(nums[end]);
result.push_back(tmp);
start++;
while(start < end && nums[start] == nums[start - 1])
start++;
} else {
end--;
while(start < end && nums[end] == nums[end+1])
end--;
}
}
}
return result;
}
};