题目

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. python 与 matlab 混编

    用于 Python 的 MATLAB 引擎 API 快速入门 安装用于 Python 的 MATLAB 引擎 API Matlab的官方文档中介绍了 Matlab 与其余编程语言之间的引擎接口,其中包 ...

  2. 在 Pandas 中更改列的数据类型

    import pandas as pd import numpy as np a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0' ...

  3. JAVAEE——宜立方商城12:购物车实现、订单确认页面展示

    1. 学习计划 第十二天: 1.购物车实现 2.订单确认页面展示 2. 购物车的实现 2.1. 功能分析 1.购物车是一个独立的表现层工程. 2.添加购物车不要求登录.可以指定购买商品的数量. 3.展 ...

  4. Java 持久化操作

    持久化就是将内存中的数据保存起来,使之可以长期存在. 在Java中 可以做到持久化有很多种方法. 其中有: 1. 堵塞型IO,也就是我们经常说的io流: 2. 非堵塞型IO,通常称为New IO.也就 ...

  5. MacBook Apache服务

    想着如何在Mac OS下部署静态网页(纯粹的html,css,js),用惯了windows下的iis,可惜Mac OS下也许只能通过Tomcat或者Apache之类的作为部署容器.听说Mac OS下自 ...

  6. 网络数据修改工具netsed

    网络数据修改工具netsed   通过修改网络数据,可以绕过软件和防火墙的限制,达到特定的目的.Kali Linux提供一个简易数据修改工具netsed.该工具支持对TCP和UDP的数据进行修改.渗透 ...

  7. Visual Studio 2017强制更新方法

    Visual Studio 2017强制更新方法   Visual Studio 2017更新时候,用户都是根据消息提示,进行更新.这样做的好处,就是微软可以分批下发升级包,避免集中更新.不过为了早点 ...

  8. 解决python2.x文件读写编码问题

    转自: https://xrlin.github.io/%E8%A7%A3%E5%86%B3python2.x%E6%96%87%E4%BB%B6%E8%AF%BB%E5%86%99%E7%BC%96 ...

  9. git merge和git rebase的区别(转)

      Description git rebase 和 git merge 一样都是用于从一个分支获取并且合并到当前分支,但是他们采取不同的工作方式,以下面的一个工作场景说明其区别 场景:  如图所示: ...

  10. CF280C Game on Tree 期望

    期望多少次操作,我们可以看做是染黑了多少节点 那么,我们可以用期望的线性性质,求出每个节点被染黑的概率之和(权值为$1$) 一个节点$u$被染黑仅跟祖先有关 我们把$u$到祖先的链抽出来 只要选取链上 ...