3Sum
题目: 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.
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets.
分析:
首先,他要求结果的triplets有顺序,所以肯定需要O(nlogn)的sort。
除此之外,要注意每个循环的最开始需要验证nums[i] != nums[i - 1]以保证不会出现重复的数据。
最后,因为题目是3Sum是否为0,所以需要取其中一个数作为target,然后对剩余两个数做2Sum。
特别注意,在最外层做for循环的时候,i = 0 ~ size - 2是可以的,但是i = 2 ~ size是不行的,
因为你跳过重复i的时候不能保证前面的所有nums[i]都不会在被用到,所以会丢解。
解答:
class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int> > threeSum(vector<int> &nums) {
// write your code here
vector<vector<int> > res;
if (nums.size() < 3) {
return res;
}
sort(nums.begin(), nums.end() );
for (int i = 0; i < nums.size() - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
int start = i + 1;
int end = nums.size() - 1;
int target = -nums[i];
while(start < end) {
int sum = nums[start] + nums[end];
if (sum == target) {
vector<int> triple(3);
triple[0] = nums[i];
triple[1] = nums[start];
triple[2] = nums[end];
res.push_back(triple);
start++;
end--;
while (start < end && nums[start] == nums[start - 1]) {
start++;
}
while (start < end && nums[end] == nums[end + 1]) {
end--;
}
} else if (sum > target) {
end--;
} else { // sum < target
start++;
}
}
}
return res;
}
};