題目
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:
2
Explanation:
The two tuples are:
(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
解法思路(一)
- 用四重循環(huán),做一個 O(N4) 的解法,在 5004 的數(shù)量級的情況下肯定是跑不完的体啰;
- N = 500 的話,用 O(N2) 的時間復(fù)雜度的解法去跑是可行的蹦哼;
如何實現(xiàn)一個 O(N2) 的解法呢?
- 如果把 C 和 D 兩兩組合之和存進(jìn)一個 HashMap 中要糊,key 是兩兩組合之和纲熏,value 是該和出現(xiàn)的次數(shù),這個動作的時間復(fù)雜度是 O(N2);
- 那么 A 和 B 的兩兩組合之和去這個 HashMap 中匹配局劲,這個匹配的動作是 O(1) 的勺拣,而 A 和 B 的兩兩組合之和是 O(N2) 的,則總的時間復(fù)雜度是 O(2N2) = O(N2)鱼填;
解法實現(xiàn)(一)
時間復(fù)雜度
- O(N2)药有;
空間復(fù)雜度
- O(N2)
關(guān)鍵字
查找表
HashMap
二維將一維
O(N^2) 降 O(1)
package leetcode._454;
import java.util.HashMap;
public class Solution454_1 {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
HashMap<Integer, Integer> CDCombination = new HashMap<>(C.length * D.length);
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < D.length; j++) {
int CDAdd = C[i] + D[j];
if (CDCombination.containsKey(CDAdd)) {
CDCombination.put(CDAdd, CDCombination.get(CDAdd) + 1);
} else {
CDCombination.put(CDAdd, 1);
}
}
}
int combination = 0;
for (int i = 0; i < A.length; i++) {
for(int j = 0; j < B.length; j++) {
int complement = 0 - A[i] - B[j];
if (CDCombination.containsKey(complement)) {
combination += CDCombination.get(complement);
}
}
}
return combination;
}
public static void main(String[] args) {
int[] A = {1, 2};
int[] B = {-2, -1};
int[] C = {-1, 2};
int[] D = {0, 2};
int result = (new Solution454_1()).fourSumCount(A, B, C, D);;
System.out.println(result);
}
}