LeetCode-454-四數相加 II
454. 四數相加 II
難度中等382收藏分享切換為英文接收動態反饋
給定四個包含整數的數組列表 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 。
例如:
輸入:
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
解題思路 分治思想
思路:
一采用分為兩組,HashMap 存一組,另一組和 HashMap 進行比對。
這樣的話情況就可以分為三種:
HashMap 存一個數組,如 A。然后計算三個數組之和,如 BCD。時間復雜度為:O(n)+O(n^3),得到 O(n^3).
HashMap 存三個數組之和,如 ABC。然后計算一個數組,如 D。時間復雜度為:O(n^3)+O(n),得到 O(n^3).
HashMap存兩個數組之和,如AB。然后計算兩個數組之和,如 CD。時間復雜度為:O(n2)+O(n2),得到 O(n^2).
根據第二點我們可以得出要存兩個數組算兩個數組。
我們以存 AB 兩數組之和為例。首先求出 A 和 B 任意兩數之和 sumAB,以 sumAB 為 key,sumAB 出現的次數為 value,存入 hashmap 中。
然后計算 C 和 D 中任意兩數之和的相反數 sumCD,在 hashmap 中查找是否存在 key 為 sumCD。
算法時間復雜度為 O(n2)。
作者:guo-sheng-fei
鏈接:https://leetcode-cn.com/problems/4sum-ii/solution/chao-ji-rong-yi-li-jie-de-fang-fa-si-shu-xiang-jia/
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>();
//Map<Integer, Integer> map = new HashMap<>();
int res = 0;
for(int i = 0;i<A.length;i++){
for(int j= 0;j<B.length;j++){
int sumAB = A[i]+B[j];
if(map.containsKey(sumAB)) map.put(sumAB,map.get(sumAB)+1);
else map.put(sumAB,1);
}
}
for(int i = 0;i<C.length;i++){
for(int j = 0;j<D.length;j++){
int sumCD = -(C[i]+D[j]);
if(map.containsKey(sumCD)) res += map.get(sumCD);
}
}
return res;
}
}