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.
思路:排序,锁定一个节点,在后续节点中,双端扫描。
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;
}
};
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;
}
};
相关文章推荐
- 【VMCloud云平台】SCSM(八)SCSM创建请求产品
- [转]Rolling cURL: PHP并发最佳实践
- linux开机自动连接无线网络
- 特里-HDOJ-1671
- linux开机自动连接无线网络
- OOP in python DEMO
- javascriptEvent对象
- Java abstract class vs interface
- VS 2005使用map文件查找程序崩溃原因
- bzoj-2957 楼房重建
- encodeURIComponent 的作用和encodeURI的区别
- HtmlParser学习系列 -- 学习总结
- Mac上配置Ant打包工具
- 20.顺时针打印矩阵
- struts2概述
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之十一:Numerical Examples
- 写一个 docker 打击一系列手册
- 实现基于Memcache存储的Session类
- nova 详解
- sizeof和strlen