leetcode 454. 4Sum II

来源:互联网 发布:jsp网上订餐系统源码 编辑:程序博客网 时间:2024/06/05 09:45

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.

Example:

Input:A = [ 1, 2]B = [-2,-1]C = [-1, 2]D = [ 0, 2]Output:2Explanation:The two tuples are:1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
这一题我原来想了想,好像没啥好办法。然后用n^4的循环来做,不出所料地TLE了。

后来看了大神的解法,我才知道原来可以分解。将4个数组的和,转化为,两个数组的和+两个数组的和。即找出AB数组和的所有可能性,再找出CD数组和的所有可能性,再判断两个和是否加起来=0,这样把O(n^4)转化为O(n^2) 。

package leetcode;import java.util.HashMap;public class Sum_II_4_454 {public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {int count=0;int n=A.length;HashMap<Integer, Integer> mapAB=new HashMap<Integer, Integer>();for(int pointerA=0;pointerA<n;pointerA++){for(int pointerB=0;pointerB<n;pointerB++){int sum=A[pointerA]+B[pointerB];mapAB.put(sum, mapAB.getOrDefault(sum, 0)+1);}}for(int pointerC=0;pointerC<n;pointerC++){for(int pointerD=0;pointerD<n;pointerD++){int sum=C[pointerC]+D[pointerD];if(mapAB.get(-sum)!=null){count+=mapAB.get(-sum);}}}return count;}public static void main(String[] args) {// TODO Auto-generated method stubSum_II_4_454 s=new Sum_II_4_454();int[] A=new int[]{1,2};int[] B=new int[]{-2,-1};int[] C=new int[]{-1,2};int[] D=new int[]{0,2};System.out.println(s.fourSumCount(A, B, C, D));}}


首先拿出数组A、B,计算他们元素的所有可能和。将和放入hashmap中,如果有超过1对元素的和相同,那么增加map中该和的value。然后计算C、D数组元素的所有可能和,如果hashmap中存在当前和的负数,那么把最终结果加上map中这个值的vaule.

Time complexity: O(n^2)
Space complexity: O(n^2)


原创粉丝点击