forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution1.java
44 lines (35 loc) · 1.25 KB
/
Solution1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/// https://leetcode.com/problems/4sum-ii/description/
/// Author : liuyubobobo
/// Time : 2017-11-15
import java.util.HashMap;
/// Using Hash Map
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
public class Solution1 {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
if(A == null || B == null || C == null || D == null)
throw new IllegalArgumentException("Illegal argument");
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < C.length ; i ++)
for(int j = 0 ; j < D.length ; j ++){
int sum = C[i] + D[j];
if(map.containsKey(sum))
map.put(sum, map.get(sum) + 1);
else
map.put(sum, 1);
}
int res = 0;
for(int i = 0 ; i < A.length ; i ++)
for(int j = 0 ; j < B.length ; j ++)
if(map.containsKey(-A[i]-B[j]))
res += map.get(-A[i]-B[j]);
return res;
}
public static void main(String[] args) {
int[] a = {1, 2};
int[] b = {-2, -1};
int[] c = {-1, 2};
int[] d = {0, 2};
System.out.println((new Solution1()).fourSumCount(a, b, c, d));
}
}