Skip to content

Commit b792950

Browse files
authored
Create 1512-number-of-good-pairs.kt
1 parent f162e92 commit b792950

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

kotlin/1512-number-of-good-pairs.kt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// rolling count
2+
class Solution {
3+
fun numIdenticalPairs(nums: IntArray): Int {
4+
val count = HashMap<Int, Int>()
5+
var total = 0
6+
7+
for (n in nums) {
8+
count[n]?.let {
9+
total += it
10+
}
11+
count[n] = count.getOrDefault(n, 0) + 1
12+
}
13+
14+
return total
15+
}
16+
}
17+
18+
// count and use arithmetic sequence
19+
class Solution {
20+
fun numIdenticalPairs(nums: IntArray): Int {
21+
val count = HashMap<Int, Int>().apply {
22+
for (n in nums) {
23+
this[n] = getOrDefault(n, 0) + 1
24+
}
25+
}
26+
27+
var res = 0
28+
for (c in count.values) {
29+
res += c * (c - 1) / 2
30+
}
31+
32+
return res
33+
}
34+
}
35+
36+
// brute force
37+
class Solution {
38+
fun numIdenticalPairs(nums: IntArray): Int {
39+
var count = 0
40+
41+
for (i in 0 until nums.size) {
42+
for (j in i + 1 until nums.size) {
43+
if (nums[i] == nums[j]) {
44+
count++
45+
}
46+
}
47+
}
48+
49+
return count
50+
}
51+
}

0 commit comments

Comments
 (0)