题目

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. @Resource与@Autowired注解的区别(转)

    Spring不但支持自己定义的@Autowired注解,还支持由JSR-250规范定义的几个注解.如:@Resource.@PostConstruct及@PreDestroy 1.@Autowired ...

  2. Iphone6手机不同浏览器页面尺寸设计

    做移动端html5页面适配,通常要考虑很多种情况. 对于同一部手机,通常要考虑如下3点: 1. 在手机普通浏览器中打开,比如Safari浏览器,UC浏览器,QQ浏览器,360浏览器,谷歌浏览器. 2. ...

  3. 模拟Djangoweb框架

    一.需求 1.访问127.0.0.1/login,访问到login页面 2.登陆成功,跳转到登陆后的页面 3.登陆失败,跳转到登陆失败的页面 4.用户账号密码验证 二.目录结构 三.代码 day01. ...

  4. 01-学前入门.Net两种交换模式

    C/S:客户机(Client)/服务器模式(Server)Winfrom应用程序 B/S:浏览器(Browser)/服务器模式(Server)Internet应用模式

  5. 线性表之顺序栈C++实现

    线性表之顺序栈 栈是限定仅在表尾(栈顶)进行插入删除操作的线性表,FILO:先进后出 一.顺序栈的头文件:SeqStack.h //顺序栈头文件 #include<iostream> us ...

  6. PHP 笔记——自定义函数

    1. 定义函数 function function_name ([$arg_1],[$arg_2], ... [$arg_n]){ fun_body; [return arg_n;] } 在PHP中, ...

  7. codevs 2292 图灵机游戏

    2292 图灵机游戏  时间限制: 1 s  空间限制: 64000 KB  题目等级 : 黄金 Gold   题目描述 Description [Shadow 1]第二题 Shadow最近知道了图灵 ...

  8. Java并发(十九):final实现原理

    final在Java中是一个保留的关键字,可以声明成员变量.方法.类以及本地变量. 一旦你将引用声明作final,你将不能改变这个引用了,编译器会检查代码,如果你试图将变量再次初始化的话,编译器会报编 ...

  9. Mybatis框架Day01(上)

    框架课程 1 课程计划 第一天: 1.mybatis的介绍 2.Mybatis的入门 a) 使用jdbc操作数据库存在的问题 b) Mybatis的架构 c) Mybatis的入门程序 3.Dao的开 ...

  10. 【BZOJ】2730: [HNOI2012]矿场搭建【Tarjan找割点】【分联通块割点个数】

    2730: [HNOI2012]矿场搭建 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 3230  Solved: 1540[Submit][Stat ...