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, a ≤ b ≤ c)
  • 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)

方法一:

//基本的brute force方法:在eclipse上运行是可以的,也满足三元组中的非降序
//及无重复三元组的要求。但是提示超时,不accept。算法复杂度为O(n^3)
public class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> result = new ArrayList<List<Integer>>();if(nums.length < 3) return result;for(int i=0; i<nums.length; i++){for(int j=i+1; j<nums.length; j++){for(int k=j+1; k<nums.length; k++){if(nums[i]+nums[j]+nums[k] == 0){Integer[] array = {nums[i], nums[j], nums[k]};Arrays.sort(array);                //对三元组排序List<Integer> list = new ArrayList<Integer>();list.addAll(Arrays.asList(array)); //addAll方法参数只能为collectionif(!result.contains(list)){        //能够达到去除重复三元组的效果result.add(list);}}}}}return result;}
}

方法二:

/引入二分查找,要求返回数组元素值而非index,故可先排序,再找元素
//理论上,算法复杂度为O(n^2*logn),在eclipse上执行也可以(没细对比,可能有误)
//提示超时,不accept
public class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> result = new ArrayList<List<Integer>>();if(nums.length < 3) return result;Arrays.sort(nums);for(int i=0; i<nums.length; i++){for(int j=i+1; j<nums.length; j++){int head = j + 1;int tail = nums.length - 1;int needNum = -(nums[i]+nums[j]);while(head <= tail){              //二分查找int middle = (head+tail) / 2;if(nums[middle] == needNum){List<Integer> list = new ArrayList<Integer>();list.add(nums[i]);list.add(nums[j]);        //已经排序过了,无需再排序了list.add(nums[middle]);if(!result.contains(list)){result.add(list);}break;           //二分查找到结果之后,一定要break,否则head=tail时会无限循环}else if(nums[middle] > needNum){tail = middle - 1;}else if(nums[middle] < needNum){head = middle + 1;}}}}return result;}
}

方法三:(accept)

//排序花费O(nlogn),遍历花费O(n^2),总复杂度为O(n^2)
public class Solution {//主调方法public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> result = new ArrayList<List<Integer>>();if(nums.length < 3) return result;Arrays.sort(nums);for(int i=nums.length-1; i>=2; i--){   //每次取nums[i],然后在nums[0~i-1]中寻找两和为-nums[i]的if(i<nums.length-1 && nums[i]==nums[i+1]){    //遇到重复的nums[i]就跳过continue;}//方法调用,找sum为-nums[i]的pairList<List<Integer>> tempCollection = twoSum(nums, i-1, -nums[i]);for(int j=0; j<tempCollection.size(); j++){List<Integer> tempList = tempCollection.get(j);tempList.add(nums[i]);                    //把二元组扩充为三元组result.add(tempList);}}return result;}//被threeSum调用的辅助方法,思想类似于昨天twoSum中的夹逼思想,但是要注意跳过重复的元素//下面的方法中,参数nums是应经排序过的数组,故调用此方法只需要O(n)的复杂度private List<List<Integer>> twoSum(int[] nums, int end, int target) {List<List<Integer>> result = new ArrayList<List<Integer>>();if(nums.length < 2) return null;int left = 0;int right = end;while(left < right){                                     //夹逼的思想if(nums[left]+nums[right] == target){List<Integer> list = new ArrayList<Integer>();list.add(nums[left]);list.add(nums[right]);result.add(list);left++;right--;while(left<right && nums[left]==nums[left-1]){   //跳过重复的元素left++;}while(left<right && nums[right]==nums[right+1]){ //跳过重复的元素right--;}}else if(nums[left]+nums[right] > target){right--;}else if(nums[left]+nums[right] < target){left++;}}return result;}}

转载于:https://www.cnblogs.com/dosmile/p/6444433.html

LeetCode | 3 Sum相关推荐

  1. 【同113】LeetCode 129. Sum Root to Leaf Numbers

    LeetCode 129. Sum Root to Leaf Numbers Solution1:我的答案 二叉树路径和问题,类似113 /*** Definition for a binary tr ...

  2. LeetCode Path Sum III(前缀和)

    问题: 给定一个二叉树,它的每个结点都存放着一个整数值. 找出路径和等于给定数值的路径总数. 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点). 二叉树 ...

  3. LeetCode Combination Sum IV(动态规划)

    问题:给出一个数组nums和目标数target,问有多少组合形式 思路:用dp(i)表示目标数target的组合数.则有状态转移关系为dp(i)=sum(dp(i-nums[j])),其中i>= ...

  4. LeetCode Range Sum Query - Mutable(树状数组、线段树)

    问题:给出一个整数数组,求出数组从索引i到j范围内元素的总和.update(i,val)将下标i的数值更新为val 思路:第一种方式是直接根据定义,计算总和时直接计算从i到j的和 第二种方式是使用树状 ...

  5. LeetCode Two Sum III - Data structure design

    原题链接在这里:https://leetcode.com/problems/two-sum-iii-data-structure-design/ 题目: Design and implement a ...

  6. LeetCode Subarray Sum Equals K

    原题链接在这里:https://leetcode.com/problems/subarray-sum-equals-k/description/ 题目: Given an array of integ ...

  7. leetcode 907. Sum of Subarray Minimums | 907. 子数组的最小值之和(单调栈)

    题目 https://leetcode.com/problems/sum-of-subarray-minimums/ 题解 单调栈问题.参考左神算法课:https://ke.qq.com/webcou ...

  8. leetcode 371. Sum of Two Integers | 371. 两整数之和(补码运算)

    题目 https://leetcode.com/problems/sum-of-two-integers/ 题解 根据 related topics 可知,本题考察二进制运算. 第一次提交的时候,没想 ...

  9. [Leetcode]Two sum(两数之和)系列总结

    Two sum 题目 Given an array of integers, return indices of the two numbers such that they add up to a ...

  10. leetcode -- 3 sum

    3-sum 题目描写叙述: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = ...

最新文章

  1. vlc生成rtsp流
  2. SNMPM 配置 [linux windows solaris]
  3. 提取ESX/ESXI4.0脚本安装文件ks.cfg、ks-first.cfg和ks-first-safe.cfg
  4. 用html编写ASCII表,[html_css]ASCII编码表
  5. Python之web开发(二):python使用django框架搭建网站之新建文件
  6. QDoc主题命令Topic Commands
  7. 3.《SQLSERVER2012之T-SQL教程》T-SQL单表查询(三)
  8. LeetCode 1428. 至少有一个 1 的最左端列(二分查找)
  9. 守得云开见月明:一次ASM存储高可用故障解决过程分析
  10. 吓坏了!智能锁半夜自己“离奇打开”
  11. junit单元测试详解
  12. 基于netty,hessian的RPC框架
  13. Nask汇编编写操作系统,自制NaskCode开发环境
  14. oracle x$bh 权限,关于Oracle的事务
  15. 计算机开机时间设置方法,win10系统设置电脑开关机时间的技巧介绍
  16. JavaEE企业级实战项目 智牛股第六天 股票交易过程
  17. System32/SysWow64
  18. matlab 圣诞树,搞气氛!用MATLAB画一棵Bling Bling的圣诞树
  19. 什么是MTTF,MTBF,MTRF
  20. 【学习笔记】要学的东西

热门文章

  1. 算法导论-VLSI芯片测试问题
  2. Mysql:SQL语句:DML语句
  3. Android应用程序管理系列(二)——PackageManager 包管理者
  4. jQuery源码解析(1)—— jq基础、data缓存系统
  5. [shell] while read line 与for循环的区别
  6. python全栈学习--day8
  7. 第10章 bit_vector位向量容器
  8. 解决长email在表格td中不自动换行的问题 CSS强制不换行
  9. ASP.NET 未被授权访问所请求的资源。请考虑授予 ASP.NET 请求标识访问此资源的?...
  10. 自考--网络经济与企业管理--选择易考题