-
Notifications
You must be signed in to change notification settings - Fork 8
/
Solution.kt
47 lines (44 loc) · 1.41 KB
/
Solution.kt
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 / 48 test cases passed.
* Status: Accepted
* Runtime: 888 ms
*/
class Solution {
fun fourSumCount(A: IntArray, B: IntArray, C: IntArray, D: IntArray): Int {
val store = HashMap<Int, Int>()
C.forEach { i ->
D.forEach { j ->
// val v = store[i + j]
// if (v == null) store[i + j] = 1 else store[i + j] = v + 1
store[i + j] = (store[i + j] ?: 0) + 1
}
}
var res = 0
A.forEach { i ->
B.forEach { j ->
// res += store.getOrDefault(0 - i - j, 0)
store[0 - i - j]?.let { res += it }
}
}
return res
}
}
/**
* 48 / 48 test cases passed.
* Status: Accepted
* Runtime: 936 ms
*/
class Solution2 {
fun fourSumCount(A: IntArray, B: IntArray, C: IntArray, D: IntArray): Int {
val store = HashMap<Int, Int>()
var res = 0
dualForEach(C, D, { i, j -> store[i + j] = (store[i + j] ?: 0) + 1 })
dualForEach(A, B, { i, j -> store[0 - i - j]?.let { res += it } })
return res
}
private inline fun dualForEach(a: IntArray, b: IntArray, forEachDo: (i: Int, j: Int) -> Unit)
: Unit = a.forEach { i -> b.forEach { j -> forEachDo(i, j) } }
}
fun main(args: Array<String>) {
Solution2().fourSumCount(intArrayOf(1, 2), intArrayOf(-2, -1), intArrayOf(-1, 2), intArrayOf(0, 2)).let(::println)
}