-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path454_4Sum_II.java
More file actions
32 lines (29 loc) · 1 KB
/
Copy path454_4Sum_II.java
File metadata and controls
32 lines (29 loc) · 1 KB
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
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int result = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//Step 1: Take the arrays A and B, and compute all the possible sums of two elements
for (int a: A) {
for (int b: B){
int sum = a + b;
//Put the sum in the Hash map
if (map.containsKey(sum)){
//increase the hash map value if more than 1 pair sums to the same value
map.put(sum, map.get(sum) + 1);
} else{
map.put(sum, 1);
}
}
}
for (int c: C) {
for (int d: D){
//a + b + c + d = 0 => a + b = - (c + d)
int sum = -(c + d);
if (map.containsKey(sum)){
result+= map.get(sum);
}
}
}
return result;
}
}