15. 3Sum

  • Total Accepted: 131800
  • Total Submissions: 675028
  • Difficulty: Medium

  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: The solution set must not contain duplicate triplets.

  

  For example, given array S = [-1, 0, 1, 2, -1, -4],

  1. A solution set is:
  2. [
  3. [-1, 0, 1],
  4. [-1, -1, 2]
  5. ]
  6.  
  7. 思路:
      首先说点题外话,对于2Sum3Sum,以及后面的4SumkSum等是一个系列的,具体的讨论在这篇文章中有提到,大家感兴趣的可以看看:http://www.sigmainfy.com/blog/summary-of-ksum-problems.html
  1.   回到正文,这道题很容易想到的是暴力解法,这也是我们通常采用的办法,但是这样的方法的复杂度是On3),再加上去重的复杂度,这样的代码在leetcode是无法成功运行的。
  2.  
  3.   对于简化的思路,我自己没有想出来,网上参考的是:LeetCode3Sum 解题报告

  我们不妨先对数组排个序。排序之后,我们就可以对数组用两个指针分别从前后两端向中间扫描了,如果是 2Sum,我们找到两个指针之和为target就OK了,那 3Sum 类似,我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。代码不难,先看了再说。

  1. public class No_015 {
  2. /*
  3. * 方法一:暴力解法
  4. */
  5. public List<List<Integer>> threeSum(int[] nums) {
  6. List<List<Integer>> res = new ArrayList<List<Integer>>() ;
  7. if(nums == null || nums.length < 3){
  8. return res ;
  9. }
  10. List<Integer> list = null ;
  11. for(int i = 0 ; i < nums.length-2 ; i++){
  12. for(int j = i+1 ; j < nums.length-1 ; j++){
  13. for(int k = j+1 ; k < nums.length ; k++){
  14. if((nums[i] + nums[j] + nums[k]) == 0){
  15. list = toRange(nums,i,j,k) ;
  16. if(!isContain(res,list)){
  17. res.add(list) ;
  18. }
  19. }
  20. }
  21. }
  22. }
  23. return res ;
  24. }
  25.  
  26. /*
  27. * 对三个数之和为0的数加入list的时候进行排序,方便后面去重
  28. *
  29. * 唉,怎么没想到一开始就对曾格格数组进行排序呢???
  30. */
  31. private List<Integer> toRange(int [] nums ,int i , int j , int k){
  32. List<Integer> list = new ArrayList<Integer>() ;
  33. int max = nums[i]>nums[j]?nums[i]:nums[j] ;
  34. int min = nums[i]+nums[j]-max ;
  35. max = max>nums[k]?max:nums[k] ;
  36. min = min<nums[k]?min:nums[k] ;
  37. list.add(min) ;
  38. list.add(nums[i]+nums[j]+nums[k]-max-min) ;
  39. list.add(max) ;
  40. return list ;
  41. }
  42. /*
  43. * 检查是否有重复
  44. */
  45. private boolean isContain(List<List<Integer>> res , List<Integer> list){
  46. if(res == null || res.size() == 0){
  47. return false ;
  48. }
  49. for(List<Integer> each:res){
  50. if(each.get(0) == list.get(0) && each.get(1) == list.get(1)){
  51. return true ;
  52. }
  53. }
  54. return false ;
  55. }
  56.  
  57. /*
  58. * 方法二:首先进行排序,然后根据排序之后的数组,从两边到中间的办法查询,这样复杂度为o(n^2)
  59. */
  60. List<List<Integer>> ret = new ArrayList<List<Integer>>();
  61. public List<List<Integer>> threeSum2(int[] num) {
  62.  
  63. if (num == null || num.length < 3)
  64. return ret;
  65.  
  66. Arrays.sort(num);
  67.  
  68. int len = num.length;
  69. for (int i = 0; i < len - 2; i++) {
  70. if (i > 0 && num[i] == num[i - 1])
  71. continue;
  72. find(num, i + 1, len - 1, num[i]); // 寻找两个数与num[i]的和为0
  73. }
  74.  
  75. return ret;
  76. }
  77.  
  78. public void find(int[] num, int begin, int end, int target) {
  79. int l = begin, r = end;
  80. while (l < r) {
  81. if (num[l] + num[r] + target == 0) {
  82. List<Integer> ans = new ArrayList<Integer>();
  83. ans.add(target);
  84. ans.add(num[l]);
  85. ans.add(num[r]);
  86. ret.add(ans); // 放入结果集中
  87. while (l < r && num[l] == num[l + 1])
  88. l++;
  89. while (l < r && num[r] == num[r - 1])
  90. r--;
  91. l++;
  92. r--;
  93. } else if (num[l] + num[r] + target < 0) {
  94. l++;
  95. } else {
  96. r--;
  97. }
  98. }
  99. }
  100.  
  101. }
  1.  

No.015 3Sum的更多相关文章

  1. 【JAVA、C++】LeetCode 015 3Sum

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  2. [Leetcode][015] 3Sum (Java)

    题目在这里: https://leetcode.com/problems/3sum/ [标签] Array; Two Pointers [个人分析] 老实交待,这个题卡半天,第一次做不会,抄别人的.过 ...

  3. LeetCode--No.015 3Sum

    15. 3Sum Total Accepted: 131800 Total Submissions: 675028 Difficulty: Medium Given an array S of n i ...

  4. 015 3Sum 三个数的和为目标数字

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  5. [Leetcode]015. 3Sum

    public class Solution { public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num ...

  6. 【LeetCode】015 3Sum

    题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find al ...

  7. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  8. 《LeetBook》leetcode题解(15):3Sum[M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  9. [目录][Leetcode] Leetcode 题解索引

    之前想边做题边写结题报告,发现有点力不从心,而且很多地方也是一知半解,现在重新做题,重新理解.这篇文章主要起一个目录的作用. 目前没有什么特定的顺序,基本都是看心情翻牌的,哈哈~ 我在Github上新 ...

随机推荐

  1. Linux提供两个格式化错误信息的函数

    #include “stdio.h” Void perror(__const char *__s); 其中__s是出现错误的地方,函数向标准错误输出设备输出如下:s:错误的详细信息. Eg.perro ...

  2. SQL升级脚本实现按版本差异化升级(优化)

    1.增加了对SQL Server 2000的兼容: 2.支持对脚本目录的批量处理: 3.将脚本版本的判断放到具体的升级子脚本中去,让调度脚本更固化. -- 根据SQL的版本好确定启用xp_cmdshe ...

  3. SAP web 开发 (第二篇 bsp 开发 mvc模式 Part2 )

    单击第一个图标,第一个图标突出显示,单击第二个图标,第一个变灰,第二个突出显示,反之一样.单击history读取历史记录. Controller ZCL_SUS_C_ORDER_CHANGE 1.   ...

  4. c++嵌套类-内存分配

    首先看下列代码:int main(){    double *p;    printf("sizeof(int):%d\nsizeof(double):%d\nsizeof(ptr):%d\ ...

  5. __attribute__ 你知多少?

    GNU C 的一大特色就是__attribute__ 机制.__attribute__ 可以设置函数属性(Function Attribute ).变量属性(Variable Attribute )和 ...

  6. [转]http://lua-users.org/wiki/LpegTutorial

    Simple Matching LPeg is a powerful notation for matching text data, which is more capable than Lua s ...

  7. attention 机制

    参考:modeling visual attention via selective tuning attention问题定义: 具体地, 1) the need for region of inte ...

  8. python-内置函数、装饰器

    本节内容:一之前课程回顾: 在书写代码的时候,先写简单的逻辑在写复杂的逻辑.概念梳理:1.函数在传递实参的时候是传递的是引用而不是从内存中重新赋相同值给形参.比如: def test(x): x.ap ...

  9. H5版俄罗斯方块(1)---需求分析和目标创新

    前言: 俄罗斯方块和五子棋一样, 规则简单, 上手容易. 几乎每个开发者, 都会在其青春年华时, 签下"xx到此一游". 犹记得大一老师在布置大程作业的时候提过: "什么 ...

  10. Sprint第二个冲刺(第十二天)

    一.Sprint 计划会议: 现在商家上传商品的图片的功能已经完成了,正在准备是实现更新商品图片.更新商品价格和商品描述得功能,目前工作进展顺利,进度也慢慢赶上,争取顺利完成目标. 下面是真机测试下的 ...