Given an array S of n integers, are there elements abc 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;
};

最新文章

  1. asp.net MVC4——省市三级联动数据库
  2. 解决web中的乱码
  3. JS中的window.setTimeout()详解
  4. .bat脚本基本命令语法
  5. [转]asp.net mvc 从数据库中读取图片
  6. 判断List、Map、Set是否为空及效率比较
  7. 体验VS2017的Live Unit Testing
  8. Linux 组配置文件(/etc/group)
  9. HDU 2412 Farm Irrigation
  10. 解决无法make uImage的问题
  11. slf4j 和 log4j的关系及合用Maven配置
  12. jQuery 获取不到 kindeditor 内容 的解决方法
  13. lumen----------lumen如何安装和使用redis第三方包扩展
  14. 【java线程】锁机制
  15. 第43章:MongoDB-集群--Sharding(分片)--多机的搭建
  16. 利用(CMD)在Django中创建文件
  17. 一个汇编的HelloWorld!
  18. dirname(__FILE__) === __DIR__
  19. 基于SSD固态硬盘的数据库性能优化
  20. OpenGL学习脚印:背面剔除(Face Culling)

热门文章

  1. New Concept English Two 15 37
  2. QLoo graphql engine 学习一 基本试用(docker&amp;&amp;docker-compose)
  3. PostgreSQL性能极限
  4. oracle12c之 表空间维护总结
  5. vue 整合雪碧图功能
  6. postman 前置 和 后置 处理器 用法
  7. Java LinkedList 和 ArrayList
  8. python mysql模块
  9. 无法正确解析FreeMarker视图
  10. Microsoft SQL Server on Linux破解 2G内存限制