15. 3Sum

  • Total Accepted: 131800
  • Total Submissions: 675028
  • Difficulty: Medium

  Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

  Note: 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]
] 思路:
  首先说点题外话,对于2Sum,3Sum,以及后面的4Sum,kSum等是一个系列的,具体的讨论在这篇文章中有提到,大家感兴趣的可以看看:http://www.sigmainfy.com/blog/summary-of-ksum-problems.html
  回到正文,这道题很容易想到的是暴力解法,这也是我们通常采用的办法,但是这样的方法的复杂度是O(n3),再加上去重的复杂度,这样的代码在leetcode是无法成功运行的。

  对于简化的思路,我自己没有想出来,网上参考的是:【LeetCode】3Sum 解题报告

  我们不妨先对数组排个序。排序之后,我们就可以对数组用两个指针分别从前后两端向中间扫描了,如果是 2Sum,我们找到两个指针之和为target就OK了,那 3Sum 类似,我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。代码不难,先看了再说。

 public class No_015 {
/*
* 方法一:暴力解法
*/
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>() ;
if(nums == null || nums.length < 3){
return res ;
}
List<Integer> list = null ;
for(int i = 0 ; i < nums.length-2 ; i++){
for(int j = i+1 ; j < nums.length-1 ; j++){
for(int k = j+1 ; k < nums.length ; k++){
if((nums[i] + nums[j] + nums[k]) == 0){
list = toRange(nums,i,j,k) ;
if(!isContain(res,list)){
res.add(list) ;
}
}
}
}
}
return res ;
} /*
* 对三个数之和为0的数加入list的时候进行排序,方便后面去重
*
* 唉,怎么没想到一开始就对曾格格数组进行排序呢???
*/
private List<Integer> toRange(int [] nums ,int i , int j , int k){
List<Integer> list = new ArrayList<Integer>() ;
int max = nums[i]>nums[j]?nums[i]:nums[j] ;
int min = nums[i]+nums[j]-max ;
max = max>nums[k]?max:nums[k] ;
min = min<nums[k]?min:nums[k] ;
list.add(min) ;
list.add(nums[i]+nums[j]+nums[k]-max-min) ;
list.add(max) ;
return list ;
}
/*
* 检查是否有重复
*/
private boolean isContain(List<List<Integer>> res , List<Integer> list){
if(res == null || res.size() == 0){
return false ;
}
for(List<Integer> each:res){
if(each.get(0) == list.get(0) && each.get(1) == list.get(1)){
return true ;
}
}
return false ;
} /*
* 方法二:首先进行排序,然后根据排序之后的数组,从两边到中间的办法查询,这样复杂度为o(n^2)
*/
List<List<Integer>> ret = new ArrayList<List<Integer>>();
public List<List<Integer>> threeSum2(int[] num) { if (num == null || num.length < 3)
return ret; Arrays.sort(num); int len = num.length;
for (int i = 0; i < len - 2; i++) {
if (i > 0 && num[i] == num[i - 1])
continue;
find(num, i + 1, len - 1, num[i]); // 寻找两个数与num[i]的和为0
} return ret;
} public void find(int[] num, int begin, int end, int target) {
int l = begin, r = end;
while (l < r) {
if (num[l] + num[r] + target == 0) {
List<Integer> ans = new ArrayList<Integer>();
ans.add(target);
ans.add(num[l]);
ans.add(num[r]);
ret.add(ans); // 放入结果集中
while (l < r && num[l] == num[l + 1])
l++;
while (l < r && num[r] == num[r - 1])
r--;
l++;
r--;
} else if (num[l] + num[r] + target < 0) {
l++;
} else {
r--;
}
}
} }
 

No.015 3Sum的更多相关文章

  1. 【JAVA、C++】LeetCode 015 3Sum

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  2. [Leetcode][015] 3Sum (Java)

    题目在这里: https://leetcode.com/problems/3sum/ [标签] Array; Two Pointers [个人分析] 老实交待,这个题卡半天,第一次做不会,抄别人的.过 ...

  3. LeetCode--No.015 3Sum

    15. 3Sum Total Accepted: 131800 Total Submissions: 675028 Difficulty: Medium Given an array S of n i ...

  4. 015 3Sum 三个数的和为目标数字

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  5. [Leetcode]015. 3Sum

    public class Solution { public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num ...

  6. 【LeetCode】015 3Sum

    题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find al ...

  7. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  8. 《LeetBook》leetcode题解(15):3Sum[M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  9. [目录][Leetcode] Leetcode 题解索引

    之前想边做题边写结题报告,发现有点力不从心,而且很多地方也是一知半解,现在重新做题,重新理解.这篇文章主要起一个目录的作用. 目前没有什么特定的顺序,基本都是看心情翻牌的,哈哈~ 我在Github上新 ...

随机推荐

  1. windowsAzure模拟器错误

    Failed to initialize Microsoft Azure storage emulator. Unable to open wait handle 无法初始化微软Azure存储模拟器. ...

  2. Javascript中封装window.open的例子

    对window.open进行封装, 使其更好用, 且更兼容, 很多人说window.open不兼容,其实不是, 因为不能直接执行, 必须通过用户手动触发才行;看代码: 代码如下 复制代码 var op ...

  3. 大量无线键盘存在KeySniffer漏洞-可嗅探用户输入的内容

    几美元的一根天线.一个无线发射器,还有几行Python代码,有了这些,黑客就可以在几十米开外主动地记录下你的用户名.密码.信用卡.你写的稿子,总之就是你用无线键盘输入的任何东西. 黑客所利用的是一种无 ...

  4. windows server 2008 r2 切换windows 7主题方法

    1. 打开Powershell 里 Cmdlets 管理角色和功能Import-Module servermanager 2. 安装桌面体验Add-WindowsFeature Desktop-Exp ...

  5. .使用 HTML+CSS 实现如图布局,border-widht 5px,一个格子大小是 50*50,hover时候边框变为红色(兼容IE6+,考虑语义化的结构)

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  6. solr异常解决

    使用solr1.4跟solr3.1时,配置了个唯一id类型是sint 或者int,启动时在tomcat后台就会抛出这个异常: org.apache.solr.common.SolrException: ...

  7. B-Tree算法分析与实现

    在数据库系统中,或者说在文件系统中,针对存储在磁盘上的数据读取和在内存中是有非常大的区别的,因为内存针对任意在其中的数据是随机访问的,然而从磁盘中读取数据是需要通过机械的方式来读取一个block,不能 ...

  8. CentOS 7 编译安装 Code::Blocks

    CentOS 7 编译安装 Code::Blocks yum install cairo-devel yum install pango-devel yum install atk-devel yum ...

  9. vi 编辑器命令 (share)

    转自:http://man.ddvip.com/soft/vieditor/vi.html 一.Unix编辑器概述 编辑器是使用计算机的重要工具之一,在各种操作系统中,编辑器都是必不可少的部件.Uni ...

  10. Appium 解决不能输入中文字符问题

    只需在初始化driver方法时,写这两行代码即可:   capabilities.setCapability("unicodeKeyboard", "True" ...