原题链接: http://oj.leetcode.com/problems/4sum/ 

这道题要求跟3Sum差点儿相同,仅仅是需求扩展到四个的数字的和了。我们还是能够依照3Sum中的解法,仅仅是在外面套一层循环。相当于求n次3Sum。我们知道3Sum的时间复杂度是O(n^2),所以假设这样解的总时间复杂度是O(n^3)。代码例如以下:

public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(num==null||num.length==0)
return res;
Arrays.sort(num);
for(int i=num.length-1;i>2;i--)
{
if(i==num.length-1 || num[i]!=num[i+1])
{
ArrayList<ArrayList<Integer>> curRes = threeSum(num,i-1,target-num[i]);
for(int j=0;j<curRes.size();j++)
{
curRes.get(j).add(num[i]);
}
res.addAll(curRes);
}
}
return res;
}
private ArrayList<ArrayList<Integer>> threeSum(int[] num, int end, int target)
{
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
for(int i=end;i>1;i--)
{
if(i==end || num[i]!=num[i+1])
{
ArrayList<ArrayList<Integer>> curRes = twoSum(num,i-1,target-num[i]);
for(int j=0;j<curRes.size();j++)
{
curRes.get(j).add(num[i]);
}
res.addAll(curRes);
}
}
return res;
}
private ArrayList<ArrayList<Integer>> twoSum(int[] num, int end, int target)
{
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
int l=0;
int r=end;
while(l<r)
{
if(num[l]+num[r]==target)
{
ArrayList<Integer> item = new ArrayList<Integer>();
item.add(num[l]);
item.add(num[r]);
res.add(item);
l++;
r--;
while(l<r&&num[l]==num[l-1])
l++;
while(l<r&&num[r]==num[r+1])
r--;
}
else if(num[l]+num[r]>target)
{
r--;
}
else
{
l++;
}
}
return res;
}

上述这样的方法比較直接。依据3Sum的结果非常easy进行推广。那么时间复杂度能不能更好呢?事实上我们能够考虑用二分法的思路,假设把全部的两两pair都求出来。然后再进行一次Two
Sum
的匹配。我们知道Two
Sum
是一个排序加上一个线性的操作,而且把全部pair的数量是O((n-1)+(n-2)+...+1)=O(n(n-1)/2)=O(n^2)。

所以对O(n^2)的排序假设不用特殊线性排序算法是O(n^2*log(n^2))=O(n^2*2logn)=O(n^2*logn),算法复杂度比上一个方法的O(n^3)是有提高的。

思路尽管明白,只是细节上会多非常多情况要处理。

首先。我们要对每个pair建一个数据结构来存储元素的值和相应的index,这样做是为了后面当找到合适的两对pair相加能得到target值时看看他们是否有重叠的index,假设有说明它们不是合法的一个结果,由于不是四个不同的元素。接下来我们还得对这些pair进行排序。所以要给pair定义comparable的函数。最后。当进行Two
Sum
的匹配时由于pair不再是一个值,所以不能像Two
Sum
中那样直接跳过同样的。每一组都得进行查看,这样就会出现反复的情况,所以我们还得给每个四个元素组成的tuple定义hashcode和相等函数,以便能够把当前求得的结果放在一个HashSet里面,这样得到新结果假设是反复的就不增加结果集了。

代码例如以下:

private ArrayList<ArrayList<Integer>> twoSum(ArrayList<Pair> pairs, int target){
HashSet<Tuple> hashSet = new HashSet<Tuple>();
int l = 0;
int r = pairs.size()-1;
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
while(l<r){
if(pairs.get(l).getSum()+pairs.get(r).getSum()==target)
{
int lEnd = l;
int rEnd = r;
while(lEnd<rEnd && pairs.get(lEnd).getSum()==pairs.get(lEnd+1).getSum())
{
lEnd++;
}
while(lEnd<rEnd && pairs.get(rEnd).getSum()==pairs.get(rEnd-1).getSum())
{
rEnd--;
}
for(int i=l;i<=lEnd;i++)
{
for(int j=r;j>=rEnd;j--)
{
if(check(pairs.get(i),pairs.get(j)))
{
ArrayList<Integer> item = new ArrayList<Integer>();
item.add(pairs.get(i).nodes[0].value);
item.add(pairs.get(i).nodes[1].value);
item.add(pairs.get(j).nodes[0].value);
item.add(pairs.get(j).nodes[1].value);
//Collections.sort(item);
Tuple tuple = new Tuple(item);
if(!hashSet.contains(tuple))
{
hashSet.add(tuple);
res.add(tuple.num);
}
}
}
}
l = lEnd+1;
r = rEnd-1;
}
else if(pairs.get(l).getSum()+pairs.get(r).getSum()>target)
{
r--;
}
else{
l++;
}
}
return res;
}
private boolean check(Pair p1, Pair p2)
{
if(p1.nodes[0].index == p2.nodes[0].index || p1.nodes[0].index == p2.nodes[1].index)
return false;
if(p1.nodes[1].index == p2.nodes[0].index || p1.nodes[1].index == p2.nodes[1].index)
return false;
return true;
}

另外一种方法比第一种方法时间上还是有提高的,事实上这道题能够推广到k-Sum的问题。基本思想就是和另外一种方法一样进行二分。然后两两结合,只是细节就非常复杂了(这点从上面的另外一种解法就能看出来),所以不是非常适合在面试中出现。有兴趣的朋友能够进一步思考或者搜索网上材料哈。

4Sum -- LeetCode的更多相关文章

  1. 4Sum——LeetCode

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  2. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  3. Solution to LeetCode Problem Set

    Here is my collection of solutions to leetcode problems. Related code can be found in this repo: htt ...

  4. [LeetCode] 4Sum II 四数之和之二

    Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...

  5. [LeetCode] 4Sum 四数之和

    Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...

  6. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  7. [LeetCode][Python]18: 4Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...

  8. LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum

    1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...

  9. leetcode — 4sum

    import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Source : https://oj.l ...

随机推荐

  1. 自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版

    Nginx比apache要好,优点很多,随便去搜寻引擎找一下就能找到一大把资料,这不是我们讨论的重点,我们的重点是自己做一个运行组合!     為何我不從網上下載一個別人已經封裝好的現成的版本呢?因為 ...

  2. ALEX WANG(王培沂)品牌_时尚频道_凤凰网

    ALEX WANG(王培沂)品牌_时尚频道_凤凰网 ALEX WANG地址: 北京朝阳区百子湾路32号苹果社区10号楼B座2205 订制热线:010-58263402

  3. Linux 各类软件整理汇总

    关于前端和后端的解释 详细链接见:http://wiki.ubuntu.org.cn/Qref/Apps Linux下程序通常不需要作为一个整体,而是模块化,于是有了可选的前端和后端——这种情况下:前 ...

  4. Android -- BroadCastReceiver的简单使用

    //首先新建一个继承自BroadcastReceiver的广播监听类 class StartActiviryReceiver extends BroadcastReceiver { public fi ...

  5. iOS 之使用CAShapeLayer中的CAGradientLayer实现圆环的颜色渐变

    本文转载自:http://blog.csdn.net/zhoutao198712/article/details/20864143 在 Github上看到一些进度条的功能,都是通过Core Graph ...

  6. ORA-00923: 未找到要求的 FROM 关键字

    oracle处理 后台数据时, select a.oga01 发货单号,e.imaud04 箱/套from oga_file a left join ogb_file b on b.ogb01 = a ...

  7. iOS NSRuntime机制

    什么是Objective-C runtime? 简单来说,Objective-C runtime是一个实现Objective-C语言的C库.对象可以用C语言中的结构体表示,而方法(methods)可以 ...

  8. [Swust OJ 649]--NBA Finals(dp,后台略(hen)坑)

    题目链接:http://acm.swust.edu.cn/problem/649/ Time limit(ms): 1000 Memory limit(kb): 65535 Consider two ...

  9. BZOJ 3282: Tree( LCT )

    LCT.. -------------------------------------------------------------------------------- #include<c ...

  10. 五张图概括 什么是 ASP 、 ASP.NET (Web Pages,Web Forms ,MVC )

    当你看懂下面这五张图,我相信你对于学习.NET Web开发路线将不陌生!                                               来源: http://www.w3 ...