题目:
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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
链接:3Sum
解法:排序,之后拿出第一个数,转化为两数和问题,注意外层循环到倒数第三个数。时间O(n^2)
class Solution {
public:
vector<vector<int> > threeSum(vector<int>& nums) {
vector<int> numSet(3);
vector< vector<int> > ans;
sort(nums.begin(), nums.end());
int sum;
int len = nums.size();
for(int i = 0; i < len - 2; i++) {
sum = 0 - nums[i];
numSet[0] = nums[i];
for(int j = i + 1, k = len - 1; j < k;) {
if(nums[j] + nums[k] == sum) {
numSet[1] = nums[j++];
numSet[2] = nums[k--];
ans.push_back(numSet);
while(j < k && nums[j] == nums[j-1])
j++;
while(j < k && nums[k] == nums[k+1])
k--;
}
else if(nums[j] + nums[k] < sum)
j++;
else
k--;
}
while(i < len - 2 && nums[i + 1] == nums[i])
i++;
}
return ans;
}
};
Runtime: 109 ms