题目

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. supervisor安装(sentos7)

    其实现在网络上supervisor的教程有很多,比较杂,我找了几个对我来说是有帮助的教程,再结合自己的理解做一些笔记,可以供自己以后翻看. 链接:https://www.cnblogs.com/Hai ...

  2. Ubuntu18.04 之jdk安装与环境配置

    1.oracle官网下载压缩包. 下载地址为: https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133 ...

  3. [代码审计]XiaoCms(后台任意文件上传至getshell,任意目录删除,会话固定漏洞)

    0x00 前言 这段时间就一直在搞代码审计了.针对自己的审计方法做一下总结,记录一下步骤. 审计没他,基础要牢,思路要清晰,姿势要多且正. 下面是自己审计的步骤,正在逐步调整,寻求效率最高. 0x01 ...

  4. AlertDialog对话框

    普通对话框 public void click1(View v) { //这里不能用 getApplicationContext()方法来获取上下文 AlertDialog.Builder build ...

  5. android activity 窗口 样式

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 将 活动 设置成 窗口样式, 可以设置 主题 为 对话框, 或者 半透明. 安卓:主题= ...

  6. 【Python3】【贪心】hdu4296 Buildings

    题意: n个板,每个板有重量和强度w和s,还有PDV值(上面的总重量-该板的强度) 对于某种叠放方式,PDV的最大值为其代表值 求该值的最小值   考虑只有两个板的情况:a和b,很显然下面的比上面的容 ...

  7. bzoj 4033

    树形DP,dp[i][j]表示i子树中,选了j个白点,i子树中所有边的贡献. /************************************************************ ...

  8. BZOJ 4419: [Shoi2013]发微博 set模拟

    4419: [Shoi2013]发微博 题目连接: http://www.lydsy.com/JudgeOnline/problem.php?id=4419 Description 刚开通的SH微博共 ...

  9. flask 中 session的源码解析

    1.首先请求上下文和应用上下文中已经知道session是一个LocalProxy()对象 2.然后需要了解整个请求流程, 3.客户端的请求进来时,会调用app.wsgi_app(),于此此时,会生成一 ...

  10. 转 UIActivityIndicatorView、UIProgressView 活动与进度指示器-IOS开发

    活动指示器(UIActivityIndicatorView)可以告知用户有一个操作正在进行中.进度指示器(UIProgressView )也具有同样功能,而且还可以告知用户离操作结束还多远. 这两个指 ...