Skip to content

Commit

Permalink
Create: 0347-top-k-frequent-elements.scala
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisKheng committed Jan 29, 2023
1 parent 8f7febc commit 4cd962d
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions scala/0347-top-k-frequent-elements.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import scala.collection.mutable.{HashMap, PriorityQueue, ListBuffer, ArrayBuffer}

object Solution {
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
val map = getNumCountMap(nums)
val arr = Array.fill(nums.length + 1)(ListBuffer[Int]())
map.foreach{case (num, count) => arr(count) += num}
arr.reverseIterator.flatten.take(k).toArray
}

def getNumCountMap(nums: Array[Int]): HashMap[Int, Int] = {
val map = HashMap[Int, Int]()
nums.foreach(num => {
map(num) = map.getOrElse(num, 0) + 1
})

map
}
}

0 comments on commit 4cd962d

Please sign in to comment.