Skip to content

Commit 40f429f

Browse files
committed
update 0347-top-k-frequent-elements.scala (better memory usage)
1 parent 4c7749d commit 40f429f

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed
Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,29 @@
1-
import scala.collection.mutable.{HashMap, PriorityQueue, ListBuffer, ArrayBuffer}
2-
1+
import scala.collection.mutable.{Map => MMap}
32
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
3+
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
4+
// number -> count
5+
val numberCountMap: MMap[Int, Int] = MMap[Int, Int]()
6+
def traverseAndUpdateMap(rem: Array[Int]): Unit = {
7+
if(rem.isEmpty) ()
8+
else {
9+
numberCountMap.updateWith(rem.head) {
10+
case Some(value) => Some(value + 1)
11+
case None => Some(1)
12+
}
13+
traverseAndUpdateMap(rem.tail)
14+
}
915
}
1016

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
17+
implicit val ordering: Ordering[(Int, Int)] = {
18+
Ordering.by[(Int, Int), Int](_._2).reverse
1819
}
19-
}
20+
21+
traverseAndUpdateMap(nums)
22+
23+
numberCountMap
24+
.toArray
25+
.sorted
26+
.take(k)
27+
.map(_._1)
28+
}
29+
}

0 commit comments

Comments
 (0)