Leetcode[15]-3Sum
2015-06-09 18:46
369 查看
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},
分析:根据题意,我们可以要找出三个数相加等于0的这样的一个集合,所以采用二维数组存储。
首先抽取一个变量出来,该变量从左往右递归遍历,递归的同时设置两个变量,让其一个从第一个变量的右边,一个从数组的末端,同步的向中间遍历,有点类似于快速排序的判断方式,
如果三个数相加小于零,则让第二个变量自加;
如果三个数相加大于零,则让第三个变量自减;
如果三个数相加等于零,则将三个数加入到数组中,然后让第二个变量和第三个变量同步增减,自增自减的过程中要判断是否有重复数字;
依次递归,直到第一个变量条件终止为止。
Code(c++):
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)
分析:根据题意,我们可以要找出三个数相加等于0的这样的一个集合,所以采用二维数组存储。
首先抽取一个变量出来,该变量从左往右递归遍历,递归的同时设置两个变量,让其一个从第一个变量的右边,一个从数组的末端,同步的向中间遍历,有点类似于快速排序的判断方式,
如果三个数相加小于零,则让第二个变量自加;
如果三个数相加大于零,则让第三个变量自减;
如果三个数相加等于零,则将三个数加入到数组中,然后让第二个变量和第三个变量同步增减,自增自减的过程中要判断是否有重复数字;
依次递归,直到第一个变量条件终止为止。
Code(c++):
class Solution { public: vector<vector<int> > threeSum(vector<int> &nums) { vector<vector<int> > result; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i++){ if(i > 0 && nums[i] == nums[i-1]) continue; threeNumber(nums, result, i); } return result; } //return vector<vector<int> > results void threeNumber(vector<int> &nums, vector<vector<int> > &results, int curIndex) { int i = curIndex + 1; int j = nums.size()-1; while(i < j){ if(nums[curIndex] + nums[i] + nums[j] < 0) i++; else if(nums[curIndex] + nums[i] + nums[j] > 0) j--; else{ vector<int> v; v.push_back(nums[curIndex]); v.push_back(nums[i]); v.push_back(nums[j]); results.push_back(v); i++; j--; while(i < j && nums[i]==nums[i - 1]) i++; while(j > i && nums[j] == nums[j + 1]) j--; } } } };
相关文章推荐
- android xml 的解析.
- AABB边框、OBB边框、通过比较球包围
- JavaScript和angularJs语法支持严格模式:”use strict”
- 菜鸟学习网络协议软件Quagga,修改ospfd vty端口和编译安装
- OC5_构造方法与self指针
- 一点小感想
- 正则表达式校验 android
- BitmapDrawable
- listen()函数中backlog参数分析
- 利用Tamper绕过防注入代码进行注入(转自 i春秋 )
- 初学MFC——位图无法显示
- hdoj1069_Monkey and Banana(dp)
- String类实现
- android:inputType参数类型说明
- STL学习笔记之容器--list(二)源码剖析
- python shell中python os模块实用函数(含改变当前工作路径、显示当前目录等)
- TCP发送接口(如send(),write()等)的返回值与成功发送到接收端的数据量无直接关系
- hdu 1205 :吃糖果
- Android 取view的cache图片
- SPH fluid simulation methods & source codes (cpu & gpu)