-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
FourSumII.java
31 lines (27 loc) · 898 Bytes
/
FourSumII.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
package problems.medium;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sherxon on 1/13/17.
* Time complexity: O(n^2)
* Space complexity: O(n^2)
*/
public class FourSumII {
public int fourSumCount(int[] a, int[] b, int[] c, int[] d) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < a.length; i++)
for (int j = 0; j < b.length; j++)
if (!map.containsKey(a[i] + b[j]))
map.put(a[i] + b[j], 1);
else
map.put(a[i] + b[j], map.get(a[i] + b[j]) + 1);
int counter = 0;
for (int i = 0; i < c.length; i++)
for (int j = 0; j < d.length; j++) {
int target = 0 - (c[i] + d[j]);
if (map.containsKey(target))
counter += map.get(target);
}
return counter;
}
}