15.3Sum (Two-Pointers)
2024-08-27 11:10:43
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:
- 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.
思路:首先大循环第一个数,从第一个数之后首尾指针向中间夹逼,时间复杂度O(n2)。需要注意跳过重复的数字。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int size = nums.size();
if(size < ) return result; sort(nums.begin(), nums.end());
find(nums, , size-, -nums[]);
for(int i = ; i < size-; i++){
if(nums[i]!=nums[i-]) find(nums, i+, size-, -nums[i]);
}
return result;
}
void find(vector<int>& nums, int start, int end, int target){
int sum;
while(start<end){
sum = nums[start]+nums[end];
if(sum == target){
item.clear();
item.push_back(-target);
item.push_back(nums[start]);
item.push_back(nums[end]);
result.push_back(item);
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
do{
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else if(sum>target){
do{
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else{
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
}
}
} private:
vector<vector<int>> result;
vector<int> item;
};
最新文章
- asp.net MVC4——省市三级联动数据库
- 解决web中的乱码
- JS中的window.setTimeout()详解
- .bat脚本基本命令语法
- [转]asp.net mvc 从数据库中读取图片
- 判断List、Map、Set是否为空及效率比较
- 体验VS2017的Live Unit Testing
- Linux 组配置文件(/etc/group)
- HDU 2412 Farm Irrigation
- 解决无法make uImage的问题
- slf4j 和 log4j的关系及合用Maven配置
- jQuery 获取不到 kindeditor 内容 的解决方法
- lumen----------lumen如何安装和使用redis第三方包扩展
- 【java线程】锁机制
- 第43章:MongoDB-集群--Sharding(分片)--多机的搭建
- 利用(CMD)在Django中创建文件
- 一个汇编的HelloWorld!
- dirname(__FILE__) === __DIR__
- 基于SSD固态硬盘的数据库性能优化
- OpenGL学习脚印:背面剔除(Face Culling)