leetcode454. 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 -228to 228\- 1 and the result is guaranteed to be at most 2^31- 1.

**Example:**

**Input:**
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

**Output:**
2

**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

現有四個等長且無序的整數數組,先要求從這四個數組中分別取一個數字,使得它們的和爲0,問這四個數組中共有多少滿足條件的數字集合。

思路和代碼

採用一些歸併排序的思路,假如我們將A,B中所有數字排列組合能夠構成的結果計算出來,再將C,D中所有數字的排列組合結果計算出來,則只需要針對AB中的值找到CD中是否有對應的負數存在即可。這裏除了要記錄數組元素的和,還要記錄該求和出現了幾次。代碼如下:

    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        if (A==null || A.length == 0) return 0;

        Map<Integer, Integer> sumMapAB = new HashMap<>(A.length * B.length);
        Map<Integer, Integer> sumMapCD = new HashMap<>(C.length * D.length);

        for (int i = 0 ; i<A.length ; i++) {
            for(int j = 0 ; j<B.length ; j++) {
                sumMapAB.put(A[i] + B[j], sumMapAB.getOrDefault(A[i] + B[j], 0) + 1);
                sumMapCD.put(C[i] + D[j], sumMapCD.getOrDefault(C[i] + D[j], 0) + 1);
            }
        }
        int count = 0;
        for (Integer key : sumMapAB.keySet()) {
            if (sumMapCD.containsKey(-key)) {
                count += sumMapAB.get(key) * sumMapCD.get(-key);
            }
        }
        return count;
    }

這裏可以空間複雜度進行優化,其實我們無序將CD的元素和也保存下來,只需要每次在計算C和D的元素和的時候直接去AB和中查找有無對應的負數即可。

    public int fourSumCount2(int[] A, int[] B, int[] C, int[] D) {
        if (A==null || A.length == 0) return 0;

        Map<Integer, Integer> sumMapAB = new HashMap<>(A.length * B.length);

        for (int i = 0 ; i<A.length ; i++) {
            for(int j = 0 ; j<B.length ; j++) {
                sumMapAB.merge(A[i] + B[j], 1, Integer::sum);
            }
        }
        int count = 0;
        for (int c : C) {
            for (int d : D) {
                count += sumMapAB.getOrDefault(-c-d, 0);
            }
        }
        return count;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章