LeetCode15:3Sum
2015-06-29 17:10
399 查看
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.
For example, given array S = {-1 0 1 2 -1 -4},
这道题可以用求两个数的和相同的解法来求解。需要注意的是对重复元素的处理,如果不加上这个减枝处理,在leetcode中会显示超时。
首先对数组进行排序,时间复杂度是O(Nlog(N))。
然后定义三个指针,第一个指针从头遍历到尾,第二个指针和第三个指针和求两个数的和时的那两个指针一样从两端开始遍历,左端由第一个指针来确定。这样时间复杂度是O(N^2)。总的时间复杂度是O(N^2)。一定要加上对重复元素的减枝处理。
runtime:68ms
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)
这道题可以用求两个数的和相同的解法来求解。需要注意的是对重复元素的处理,如果不加上这个减枝处理,在leetcode中会显示超时。
首先对数组进行排序,时间复杂度是O(Nlog(N))。
然后定义三个指针,第一个指针从头遍历到尾,第二个指针和第三个指针和求两个数的和时的那两个指针一样从两端开始遍历,左端由第一个指针来确定。这样时间复杂度是O(N^2)。总的时间复杂度是O(N^2)。一定要加上对重复元素的减枝处理。
runtime:68ms
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { int length=nums.size(); vector<vector<int>> result; if(length<3) return result; sort(nums.begin(),nums.end()); auto iter1=nums.begin(); for(;iter1!=nums.end()-2;iter1++) { auto iter2=iter1+1; auto iter3=nums.end()-1; while(iter2<iter3) { if(*iter1+*iter2+*iter3==0) { vector<int> tmp; tmp.push_back(*iter1); tmp.push_back(*iter2); tmp.push_back(*iter3); result.push_back(tmp); while(*iter2==*(iter2+1)&&(iter2+1)<iter3) iter2++; while(*iter3==*(iter3-1)&&iter2<(iter3-1)) iter3--; iter2++; } else if(*iter1+*iter2+*iter3<0) { while(*iter2==*(iter2+1)&&(iter2+1)<iter3) iter2++; iter2++; } else { while(*iter3==*(iter3-1)&&iter2<(iter3-1)) iter3--; iter3--; } } while(*iter1==*(iter1+1)&&(iter1+1)<nums.end()-2) iter1++; } return result; } };
相关文章推荐
- java基础入门-arraylist存储开销
- angularjs 表单验证
- MySQL模拟:线上误update的恢复
- java基础入门-arraylist存储开销
- 切换图片、fragment;可以控制循环、时间,添加下标及下标设置,fragment 添加标题及标题设置
- flash builder 4.6在debug调试时需要系统安装flashplayer debug版本
- VC 常见问题百问
- Android Activity或者是对话框等设置透明和半透明
- 115.按规定存放数
- linux 安装svn,并设置钩子来同步更新
- 第1章 游戏之乐——双线程高效下载
- 发布windows服务的批处理
- 图标字体化浅谈
- 自定义组件—ListView_加头去头,加脚去脚、添加或删除ListView中的数据、
- [教程] 使用3D Infinite Runner Toolkit打造僵尸跑酷游戏
- sqlserver 语句中的default 是怎么用的?
- iOS 开发之数据库(SQLite)
- devexpress表格控件gridcontrol图片列,按钮列,时间列等特殊列的实现
- json学习系列(4)-JSONString对象的optXXX方法的使用
- Qt:禁止qDebug的输出