leetcode 15:3Sum
2017-02-14 18:34
309 查看
描述:
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:
1.Element in a triplet(a,b,c) must be in non-descending order.(ie,a<=b<=c)
2.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)
分析:刚看到这个题的时候,就觉得这道题是TwoSum的升级版。。暴力求解法可以做,转化为查找的方法有点麻烦,因为这是三个数相加要等于零,三个数的平衡更难些,还有一个方法就是排序后左右夹逼。。注意这个题没有要求返回下标。
由于暴力求解比较简单,所以在这里不详述了。下面我们就实现排序后左右夹逼的这种方法,时间复杂度为O(n2),类似的这个方法也可以求ksum
代码如下:
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:
1.Element in a triplet(a,b,c) must be in non-descending order.(ie,a<=b<=c)
2.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)
分析:刚看到这个题的时候,就觉得这道题是TwoSum的升级版。。暴力求解法可以做,转化为查找的方法有点麻烦,因为这是三个数相加要等于零,三个数的平衡更难些,还有一个方法就是排序后左右夹逼。。注意这个题没有要求返回下标。
由于暴力求解比较简单,所以在这里不详述了。下面我们就实现排序后左右夹逼的这种方法,时间复杂度为O(n2),类似的这个方法也可以求ksum
代码如下:
相关文章推荐
- java线上编程网站
- world分节及分节首页分节页码总页码设置方法
- expreiment to see what a callback function should be When executing a query
- Python获取邮箱内容并解析
- jbpm工作流学习手册
- 观察者模式
- border-radius属性值参数详解
- adb命令
- Crashlytics-Android崩溃(crash)统计工具使用教程
- microservice 实践
- Android HorizontalScrollView左右滑动
- java 接收ios文件上传
- 关于eclipse配置svn版本控制工具
- freemarker判断对象是否为空的方法
- dubbo起源的思考
- JBPM工作流引擎之并发流程&组任务&事件&自定义任务
- 分布式的一些基础知识
- 浅谈逆元
- (Ryan的Redis系列博客)5.Redis的键字符串类型
- COM---动态链接