4Sum -- LeetCode
原题链接: 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的更多相关文章
- 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 ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- Solution to LeetCode Problem Set
Here is my collection of solutions to leetcode problems. Related code can be found in this repo: htt ...
- [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 ...
- [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 ...
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- [LeetCode][Python]18: 4Sum
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...
- 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 ...
- leetcode — 4sum
import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Source : https://oj.l ...
随机推荐
- cmake 学习笔记(四)
接前面的一二三,学习一下 CMakeCache.txt 相关的东西. CMakeCache.txt 可以将其想象成一个配置文件(在Unix环境下,我们可以认为它等价于传递给configure的参数). ...
- BeanUtils数据封装与表单JavaBean
一.BeanUtils工具的解释 (1)Apache的Commons组件中.提供了一个实用的工具类BeanUtils,利用它可以方便的将表单数据值填充值Bean中: (2)javax.servlet. ...
- Android基调(十六)- Service:startService()、stopService()、bindService()、unbindService()加
直行 第一 另外一种 第三种 总结 开门见山 开启服务有三种情况:假设直接使用服务,则没有必要进行绑定,可是假设要使用服务里面的方法.则要进行绑定. 具体的启动情况有下: ①调用startServic ...
- 驱动: 中断【1】linux中断流程
通常情况下,当一个给定的中断处理程序正在执行时,所有其他的中断都是打开的,所以这些不同中断线上的其他中断都能被处理,但当前中断总是被禁止的. 将中断处理切为两个部分或两半.中断处理程序上半部(top ...
- [Swust OJ 137]--波浪数(hash+波浪数构造)
题目链接:http://acm.swust.edu.cn/problem/137/ Time limit(ms): 1000 Memory limit(kb): 65535 Description ...
- BZOJ 1042: [HAOI2008]硬币购物( 背包dp + 容斥原理 )
先按完全背包做一次dp, dp(x)表示x元的东西有多少种方案, 然后再容斥一下. ---------------------------------------------------------- ...
- HDU 1025 DP + 二分
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1025 求最长递增子序列,O(n^2)的复杂度超时,需要优化为O(n*logn) f[i]存储长度为i的最小 ...
- Webservice-WSDL详解(三)
怎样向别人介绍WS的功能呢?一般咱们会写接口文档,亦或口头告诉使用的人.这些方式都存在问题:其中一个我上篇中说过,客户端是无法直接使用服务端接口的:二是程序员在电脑前,想使用WS时,他们的工具(如Ec ...
- Net::OpenSSH 模块使用
use Net::OpenSSH; my $host = "$ip"; my $user = 'root'; my $passphrase = 'uxxxxxD'; my $key ...
- Mybatis3 框架理解
最近工作比较闲,维护一个政府机关的短信发送平台,大部分业务逻辑都在Oracle数据库上,但自己明明应聘的是Java开发啊!!!整天写存储过程的我还是有一颗写高级语言的心啊!!!好吧!!!先找个数据库方 ...