原题链接: 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. literal控件的例子

    Literal的Mode属性,举例说明 这个属性的枚举值:PassThrough  Encode  Transform <%@ Page Language="C#" Auto ...

  2. 17.2?Replication Implementation 复制实施:

    17.2?Replication Implementation 复制实施: 17.2.1 Replication Implementation Details 17.2.2 Replication R ...

  3. IT第十九天 - 继承、接口、多态、面向对象的编程思想

    IT第十九天 上午 继承 1.一般情况下,子类在继承父类时,会调用父类中的无参构造方法,即默认的构造方法:如果在父类中只写了有参的构造方法,这时如果在子类中继承时,就会出现报错,原因是子类继承父类时无 ...

  4. 关于String和StringBuffer的理解问题:指针、变量的声明、变量的值的变化

    问题描述: 首先,看一个小的测试程序: public static void main(String[] args) { testStringBuffer test = new testStringB ...

  5. 关于jdbc的一些疑问

    1.为什么强调在使用jdbc时,须要在使用的时候才打开连接(Connection),用完后立刻关闭.假设我的连接(Connection)一開始就打开.在整个程序结束时才关闭,会带来什么后果呢? 2.为 ...

  6. css 基础(一)

    一.css样式表的分类 首先介绍一下css中的样式表  a.外部样式表  将需要的样式放在单独的外部文件中,需要使用是直接调用,通常放在.css文件中.例如:/*以下部分是放在(my.css)自定义名 ...

  7. Android面试题整理(1)

    1.Activity的生命周期      onCreate(Bundle saveInstanceState):创建activity时调用.      onStart():activity可见时调用 ...

  8. PHP学习笔记1-常量,函数

    常量:使用const(php5)声明,只能被赋值一次,php5以下版本使用define: <?php const THE_VALUE = 100;//PHP5中才有const echo THE_ ...

  9. java --- 对象的创建过程

    java 对象创建的过程 存在了继承关系之后,对象创建过程如下: 1.分配空间.要注意的是,分配空间不光是分配子类的空间,子类对象中包含的父类对象所需要的空间,一样在这一步统一分配.在分配的空间的时候 ...

  10. jQuery中的index方法介绍

    从jq api手册摘过来的内容,index这个方法在写 tab silder 之类的组件还是比较有用的说. js没有传统的函数重载的概念,但是根据传入参数的不同,js的函数可以完成不同的功能,也可说是 ...