Skip to content

Commit 4cd962d

Browse files
committed
Create: 0347-top-k-frequent-elements.scala
1 parent 8f7febc commit 4cd962d

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import scala.collection.mutable.{HashMap, PriorityQueue, ListBuffer, ArrayBuffer}
2+
3+
object Solution {
4+
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
5+
val map = getNumCountMap(nums)
6+
val arr = Array.fill(nums.length + 1)(ListBuffer[Int]())
7+
map.foreach{case (num, count) => arr(count) += num}
8+
arr.reverseIterator.flatten.take(k).toArray
9+
}
10+
11+
def getNumCountMap(nums: Array[Int]): HashMap[Int, Int] = {
12+
val map = HashMap[Int, Int]()
13+
nums.foreach(num => {
14+
map(num) = map.getOrElse(num, 0) + 1
15+
})
16+
17+
map
18+
}
19+
}

0 commit comments

Comments
 (0)