问题:
454. 4Sum II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l)
there are such that A[i] + B[j] + C[k] + D[l]
is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
就是给你四个数组,统计四个数组数字之间和为0的情况。
首先:JAVA 中 int 32位,所以在题目设定中,求和的时候不会发生溢出的情况。
分析:
方法一:
如果用最简单的遍历时间复杂度O(N^4),
代码:
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int count=0;
int temp1 = 0;
int temp2 = 0;
final int NUM = 268435456;
final int MINGATE = -1*(NUM-1);
final int MAXGATE = NUM;
for(int k1=0;k1<A.length;k1++){
for(int k2=0;k2<A.length;k2++){
temp1 = A[k1]+B[k2];
for(int k3=0;k3<A.length;k3++){
temp2 = temp1+C[k3];
if(temp2>MAXGATE &&temp2<MINGATE){
}else{
for(int k4=0;k4<A.length;k4++){
if(temp2+D[k4]==0){
count++;
}
}
}
}
}
}
return count;
}
超时。。
方法二:转载自:http://blog.youkuaiyun.com/myfwjy/article/details/53490284
思想:
1。就是把四个数组分为两块,先预存两个数组的和(下面通过哈希的方式能够减低存储的空间开销,并且能够整合重复值(能不能降低时间
开销不敢说))然后再用另外两个数组的和比较。
时间复杂度:O(N^2)
空间复杂度: O(N^2)
代码:
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int count = 0;
Arrays.sort(A);
Arrays.sort(B);
Arrays.sort(C);
Arrays.sort(D);
HashMap<Integer,Integer> aMap = new HashMap<Integer,Integer>();
for(int i=0;i<A.length;i++){
for(int j=0;j<A.length;j++){
int sum = A[i] + B[j];
aMap.put(sum,aMap.getOrDefault(sum,0)+1);
}
}
for(int i=0;i<A.length;i++){
for(int j=0;j<A.length;j++){
int sum = C[i] + D[j];
if(aMap.containsKey(-sum)){
count += aMap.get(-sum);
}
}
}
return count;
}
运行结果:
(仅供参考)