Skip to content

Commit c2b8615

Browse files
add new files and prod variant's and change 347 problem
1 parent 8adb8c0 commit c2b8615

File tree

3 files changed

+47
-25
lines changed

3 files changed

+47
-25
lines changed

app/src/main/java/com/leetcode_kotlin/AlgorithmLeetcode.kt

-25
Original file line numberDiff line numberDiff line change
@@ -2612,31 +2612,6 @@ fun findRelativeRanks(score: IntArray): Array<String> {
26122612
return ans
26132613
}
26142614

2615-
/**
2616-
* 347. Top K Frequent Elements
2617-
*/
2618-
2619-
fun topKFrequent(nums: IntArray, k: Int): IntArray? {
2620-
val map: MutableMap<Int, Int> = HashMap()
2621-
for (n in nums) {
2622-
map[n] = map.getOrDefault(n, 0) + 1
2623-
}
2624-
2625-
val heap = PriorityQueue { a: Map.Entry<Int, Int>, b: Map.Entry<Int, Int> ->
2626-
b.value.compareTo(a.value)
2627-
}
2628-
2629-
for (entry in map.entries) {
2630-
heap.offer(entry)
2631-
}
2632-
2633-
val res = IntArray(k)
2634-
for (i in 0 until k) {
2635-
res[i] = heap.poll().key
2636-
}
2637-
2638-
return res
2639-
}
26402615

26412616
/**
26422617
* 437. Path Sum III
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.github.contest.priorityqueue
2+
3+
import java.util.PriorityQueue
4+
5+
/**
6+
* 347. Top K Frequent Elements
7+
*/
8+
9+
fun topKFrequent(nums: IntArray, k: Int): IntArray? {
10+
val map: MutableMap<Int, Int> = HashMap()
11+
for (n in nums) {
12+
map[n] = map.getOrDefault(n, 0) + 1
13+
}
14+
15+
val heap = PriorityQueue { a: Map.Entry<Int, Int>, b: Map.Entry<Int, Int> ->
16+
b.value.compareTo(a.value)
17+
}
18+
19+
for (entry in map.entries) {
20+
heap.offer(entry)
21+
}
22+
23+
val res = IntArray(k)
24+
for (i in 0 until k) {
25+
res[i] = heap.poll().key
26+
}
27+
28+
return res
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.github.contest.priorityqueue
2+
3+
/**
4+
* 347. Top K Frequent Elements
5+
*/
6+
7+
fun topKFrequentProdVariant(nums: IntArray, k: Int): IntArray {
8+
val freq = mutableMapOf<Int, Int>()
9+
val repeated = Array<MutableList<Int>>(nums.size + 1) {mutableListOf()}
10+
11+
for (num in nums) freq[num] = freq.getOrDefault(num, 0) + 1
12+
13+
for ((num, count) in freq) {
14+
repeated[count].add(num)
15+
}
16+
17+
return repeated.flatMap {it}.takeLast(k).toIntArray()
18+
}

0 commit comments

Comments
 (0)