您的位置:首页 > 其它

leetcode 015 —— 3Sum

2015-07-08 20:13 363 查看
Given an array S of n integers, are there elements a, b, c in S such that a + b + c =
0? Fi

nd all unique triplets in the array which gives the sum of zero.

Note:

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.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

思路:排序,锁定一个节点,在后续节点中,双端扫描。

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
if (n < 3) return res;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; i++){
if (i>0 && nums[i] == nums[i - 1])//序列nums是递增的,所以nums[i]能产生的组合总是<= nums[i-1]
continue;
int target = 0 - nums[i];
int start = i+1;
int end = n-1;
while (start < end){
int sum = nums[start] + nums[end];
if (sum == target){
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[start]);
tmp.push_back(nums[end]);
//cout << nums[i] << ' ' << nums[start] << ' ' << nums[end] << endl;
res.push_back(tmp);
while (start < end&&nums[start] == nums[start + 1])
start++;
while (start < end&&nums[end] == nums[end - 1])
end--;
start++; //继续往中间搜索
end--;

}
else if (sum < target)
start++;
else
end--;

}

}
return res;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: