File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments