-
Notifications
You must be signed in to change notification settings - Fork 0
/
4SumII.java
72 lines (54 loc) · 1.62 KB
/
4SumII.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
Example 1:
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
Example 2:
Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1
Constraints:
n == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
*/
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Map<Integer, Integer> map = new HashMap();
for(int d: nums4){
for(int c: nums3){
map.put(c+d, map.getOrDefault(c+d, 0)+1);
}
}
int count = 0;
for(int a: nums1){
for(int b: nums2){
count+= map.getOrDefault(-(a+b),0);
}
}
return count;
}
}
// BASIC SOLUTION:
// int count = 0;
// for(int a: nums1){
// for(int b: nums2){
// for(int c: nums3){
// for(int d: nums4){
// if(a+b+c+d ==0) count++;
// }
// }
// }
// }
// return count;
// }
// Runtime 135 ms Beats 75.21%
// Memory 43.7 MB Beats 70.60%