[leetcode]4Sum
来源:互联网 发布:税务局知乎 编辑:程序博客网 时间:2024/05/01 21:21
4Sum
题意:给定一个array,找出四个数的组合相加等于target
解法:将每两个数的和放入形如key=integer,value=arraylist<integer>的hashtable,对target-数对的和进行判断,看是否存在这样的key,并且index与数对不冲突。由于枚举过程是枚举任意两个不同的数字,而枚举的判断过程是在一个arraylist中进行,这样的list的大小是O(n^2)级别的,所以单从这一点看,算法的复杂度至少是O(N^4)。但究竟有多少这样的数对,其实取决于答案的多少。
我们可以通过对相同数字的出现次数限定不超过4次,来避免极端情况的存在。于是问题转化为,对于n个数,每个数相同的次数不超过4次,问题的答案数是否有比O(N^4)小的上届?
这个问题还值得思考,我们先采用枚举其中3个数,那么target-三个数和一定只有一个数字,由于一个数字最多出现4次,于是至少我们的算法是O(N^3)的。
是否有更紧确上届正在思考中。
import java.util.ArrayList;import java.util.HashSet;import java.util.Hashtable; public class Solution135 { classTwoIndex{ inta; intb; TwoIndex(inta,int b){ this.a=a; this.b=b; } booleanvalid(TwoIndex that){ if(that.a!=a&&that.a!=b&&that.b!=a&&that.b!=b){ returntrue; }else{ returnfalse; } } } public ArrayList<ArrayList<Integer>> fourSum(int[] num, inttarget) { ArrayList<ArrayList<Integer>>ans=new ArrayList<ArrayList<Integer>>(); HashSet<String> hashAns=newHashSet<String>(); int n=num.length; Hashtable<Integer,ArrayList<TwoIndex>>hash=new Hashtable<Integer,ArrayList<TwoIndex>>(); for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++){ intsum=num[i]+num[j]; if(!hash.containsKey(sum)){ hash.put(sum,new ArrayList<TwoIndex>()); } TwoIndex thisTwo=newTwoIndex(i,j); hash.get(sum).add(thisTwo); if (hash.containsKey(target-sum)){ ArrayList<TwoIndex>temp=hash.get(target-sum); for (intk=0;k<temp.size();k++){ TwoIndexthat=temp.get(k); if(thisTwo.valid(that)){ ArrayList<Integer>tempArr=new ArrayList<Integer>(); tempArr.add(num[thisTwo.a]); tempArr.add(num[thisTwo.b]); tempArr.add(num[that.a]); tempArr.add(num[that.b]); qsort(tempArr,0,3); StringtempS=tempArr.get(0)+" "+tempArr.get(1)+""+tempArr.get(2)+" "+tempArr.get(3); if(!hashAns.contains(tempS)){ hashAns.add(tempS); ans.add(tempArr); } } } } } } return ans; } privatevoid qsort(ArrayList<Integer> tempArr, int x, int y) { inti=x; intj=y; intt=tempArr.get((i+j)/2); do{ while(tempArr.get(i)<t){ i++; } while(tempArr.get(j)>t){ j--; } if(i<=j){ inttemp=tempArr.get(i); tempArr.set(i,tempArr.get(j)); tempArr.set(j,temp); i++; j--; } }while(i<=j); if(j>x){ qsort(tempArr,x,j); } if(i<y){ qsort(tempArr,i,y); } }}
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- 友谊是一株树
- POJ 1149 PIGS
- PHP常用函数
- ASP.NET之通过JS向服务端(后台)发出请求(__doPostBack is undefined)
- Window配置Mysql5.6.14
- [leetcode]4Sum
- VC获取窗口图片(截图)
- typedef定义函数指针
- 2014年互联网IT待遇
- linux mint下安装thrift
- php字符串处理函数大全
- Sql server 数据库的备份和还原____还原数据库提示“介质集有2个介质簇,但只提供了1个。必须提供所有成员”
- 连接查询
- Qt制作360安仔精灵