题目

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, abc)
  • 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) 题解
 3 Sum是two Sum的变种,可以利用two sum的二分查找法来解决问题。
本题比two sum增加的问题有:解决duplicate问题,3个数相加返回数值而非index。
首先,对数组进行排序。
然后,从0位置开始到倒数第三个位置(num.length-3),进行遍历,假定num[i]就是3sum中得第一个加数,然后从i+1的位置开始,进行2sum的运算。
当找到一个3sum==0的情况时,判断是否在结果hashset中出现过,没有则添加。(利用hashset的value唯一性)
因为结果不唯一,此时不能停止,继续搜索,low和high指针同时挪动。 时间复杂度是O(n2)
实现代码为:
 1     public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 3         if(num.length<3||num == null)
 4             return res;
 5         
 6         HashSet<ArrayList<Integer>> hs = new HashSet<ArrayList<Integer>>();
 7         
 8         Arrays.sort(num);
 9         
         for(int i = 0; i <= num.length-3; i++){
             int low = i+1;
             int high = num.length-1;
             while(low<high){//since they cannot be the same one, low should not equal to high
                 int sum = num[i]+num[low]+num[high];
                 if(sum == 0){
                     ArrayList<Integer> unit = new ArrayList<Integer>();
                     unit.add(num[i]);
                     unit.add(num[low]);
                     unit.add(num[high]);
                     
                     if(!hs.contains(unit)){
                         hs.add(unit);
                         res.add(unit);
                     }
                     
                     low++;
                     high--;
                 }else if(sum > 0)
                     high --;
                  else
                     low ++;
             }
         }
         
         return res;
     }

 同时,解决duplicate问题,也可以通过挪动指针来解决判断,当找到一个合格结果时,将3个加数指针挪动到与当前值不同的地方,才再进行继续判断,代码如下:
 1     public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 3         if(num.length<3||num == null)
 4             return res;
 5         
 6         Arrays.sort(num);
 7         
 8         for(int i = 0; i <= num.length-3; i++){
 9             if(i==0||num[i]!=num[i-1]){//remove dupicate
                 int low = i+1;
                 int high = num.length-1;
                 while(low<high){
                     int sum = num[i]+num[low]+num[high];
                     if(sum == 0){
                         ArrayList<Integer> unit = new ArrayList<Integer>();
                         unit.add(num[i]);
                         unit.add(num[low]);
                         unit.add(num[high]);
                         
                         res.add(unit);
                         
                         low++;
                         high--;
                         
                         while(low<high&&num[low]==num[low-1])//remove dupicate
                             low++;
                         while(low<high&&num[high]==num[high+1])//remove dupicate
                             high--;
                             
                     }else if(sum > 0)
                         high --;
                      else
                         low ++;
                 }
             }
         }
         return res;
     }

3 Sum leetcode java的更多相关文章

  1. 【LeetCode】Path Sum ---------LeetCode java 小结

    Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

  2. Minimum Path Sum leetcode java

    题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right w ...

  3. Binary Tree Maximum Path Sum leetcode java

    题目: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tr ...

  4. Path Sum leetcode java

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  5. 4 Sum leetcode java

    题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  6. Two Sum Leetcode Java

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  7. Combination Sum leetcode java

    题目: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C ...

  8. N-Queens II leetcode java

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

  9. LeetCode算法题-Path Sum(Java实现)

    这是悦乐书的第169次更新,第171篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第28题(顺位题号是112).给定二叉树和整数sum,确定树是否具有根到叶路径,使得沿路 ...

随机推荐

  1. CSUOJ 1900 锋芒不露

    Description 小闪最近迷上了二刀流--不过他耍的其实是剑--新买了一个宝库用来专门存放自己收集的双剑.一对剑有两把,分只能左手用的和只能右手用的,各自有一个攻击力数值.虽然一对剑在小闪刚拿到 ...

  2. ARM 常用汇编指令

    ARM 汇编程序的框架结构 .section .data <初始化的数据> .section.bss <未初始化的数据> .section .text .global _sta ...

  3. 在python中独立运行orm

  4. 课下测试ch17&ch18

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

  5. Codeforces Round #352 (Div. 1) B. Robin Hood 二分

    B. Robin Hood 题目连接: http://www.codeforces.com/contest/671/problem/B Description We all know the impr ...

  6. numpy中的random函数

    1:rand rand(d0, d1, ..., dn)    Random values in a given shape.    Create an array of the given shap ...

  7. 基于Landmark的人脸对齐以及裁剪方法

    利用Landmarks进行人脸对齐裁剪是人脸检测中重要的一个步骤.效果如下图所示: 基本思路为: a.人脸检测 人脸的检测不必多说了,基本Cascade的方式已经很不错了,或者用基于HOG/FHOG的 ...

  8. Git_git的诞生

    很多人都知道,Linus在1991年创建了开源的Linux,从此,Linux系统不断发展,已经成为最大的服务器系统软件了. Linus虽然创建了Linux,但Linux的壮大是靠全世界热心的志愿者参与 ...

  9. Tasker to proximity screen off

    If you are using proximity screen off pro or smart screen off, you may know how convenient it is to ...

  10. AWR--service statistics

    近期发现一个奇怪的现象,数据库报告上看负载非常高.可是cpu和等待事件都非常低,不知道消耗的资源跑到哪里去了? Snap Id Snap Time Sessions Cursors/Session B ...