­

LeetCode 454: 四數相加 II 4Sum II

  • 2019 年 12 月 16 日
  • 筆記

題目:

給定四個包含整數的數組列表 A , B , C , D ,計算有多少個元組 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0

為了使問題簡單化,所有的 A, B, C, D 具有相同的長度 N,且 0 ≤ N ≤ 500 。所有整數的範圍在 -228 到 228 – 1 之間,最終結果不會超過 231 – 1 。

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.

例如:

輸入:  A = [ 1, 2]  B = [-2,-1]  C = [-1, 2]  D = [ 0, 2]    輸出:  2    解釋:  兩個元組如下:  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

解題思路:

  • 暴力破解: 四層 for 循環, 把每一種組合都過一遍. 時間複雜度為 O(n^4)
  • 優化一: 使用一個哈希集合存儲其中的一個數組, 三層 for 循環把剩下三個數組的組合都過一遍, 並查詢哈希集合中是否存在能滿足條件的元素值存在. 時間複雜度為 O(n^3)
  • 優化二: 使用一個哈希映射, key 為兩個數組中元素組合值之和, value 為兩數和的值出現的次數(因為任意元素組合之和可能相同), 兩層 for 循環將剩餘兩個數組所有組合過一遍, 找到滿足條件的 key , 總次數與對應 value 值累加, 最優解, 時間複雜度為 O(n^2)

哈希映射解題:

Java:

class Solution {      public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {          Map<Integer, Integer> map = new HashMap<>();          int count = 0;          for (int i = 0; i < A.length; i++)              for (int j = 0; j < B.length; j++) {                  int sum = A[i] + B[j];                  map.put(sum, map.getOrDefault(sum, 0) + 1); // key 為兩個數組中元素組合值之和, value 為兩數和的值出現的次數              }          for (int i = 0; i < C.length; i++)              for (int j = 0; j < D.length; j++)                  count += map.getOrDefault(-C[i] - D[j], 0); // 找到滿足條件的 key , 總次數與對應 value 值累加 (因為value 代表 A, B 數組中符合條件的組合的次數)          return count;      }  }

Python:

class Solution:      def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:          count, hash_map = 0, dict()          for a in A:              for b in B:                  sum_ab = a+b                  hash_map.setdefault(sum_ab, 0)                  hash_map[sum_ab] += 1 # key 為兩個數組中元素組合值之和, value 為兩數和的值出現的次數          for c in C:              for d in D:                  count += hash_map.get(-c-d, 0) # 找到滿足條件的 key , 總次數與對應 value 值累加 (因為value 代表 A, B 數組中符合條件的組合的次數)          return count