LeetCode: 4Sum II

Time Complexity: O(n^2)

 1 public class Solution {
 2     public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
 3         int len = A.length;
 4         int ans = 0;
 5         Map<Integer, Integer> countAB = new HashMap<Integer, Integer>();
 6         Map<Integer, Integer> countCD = new HashMap<Integer, Integer>();
 7         for (int i = 0; i < len; i++) {
 8             for (int j = 0; j < len; j++) {
 9                 Integer g = new Integer(A[i] + B[j]);
10                 if (countAB.containsKey(g)) {
11                     int v = countAB.get(g);
12                     countAB.put(g, ++v);
13                 }
14                 else countAB.put(g, 1);
15                 g = new Integer(C[i] + D[j]);
16                 if (countCD.containsKey(g)) {
17                     int v = countCD.get(g);
18                     countCD.put(g,  ++v);
19                 }
20                 else countCD.put(g, 1);
21             }
22         }
23         for (Integer key : countAB.keySet()) {
24             if (countCD.containsKey(-key)) {
25                 ans += countAB.get(key) * countCD.get(-key);
26             }
27         }
28         return ans;
29     }
30 }
原文地址:https://www.cnblogs.com/yingzhongwen/p/6073454.html