mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加 0347.前K个高频元素.md Scala版本
This commit is contained in:
@ -374,7 +374,49 @@ function topKFrequent(nums: number[], k: number): number[] {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Scala:
|
||||||
|
|
||||||
|
解法一: 优先级队列
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
import scala.collection.mutable
|
||||||
|
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
|
||||||
|
val map = mutable.HashMap[Int, Int]()
|
||||||
|
// 将所有元素都放入Map
|
||||||
|
for (num <- nums) {
|
||||||
|
map.put(num, map.getOrElse(num, 0) + 1)
|
||||||
|
}
|
||||||
|
// 声明一个优先级队列,在函数柯里化那块需要指明排序方式
|
||||||
|
var queue = mutable.PriorityQueue[(Int, Int)]()(Ordering.fromLessThan((x, y) => x._2 > y._2))
|
||||||
|
// 将map里面的元素送入优先级队列
|
||||||
|
for (elem <- map) {
|
||||||
|
queue.enqueue(elem)
|
||||||
|
if(queue.size > k){
|
||||||
|
queue.dequeue // 如果队列元素大于k个,出队
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 最终只需要key的Array形式就可以了,return关键字可以省略
|
||||||
|
queue.map(_._1).toArray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
解法二: 相当于一个wordCount程序
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
|
||||||
|
// 首先将数据变为(x,1),然后按照x分组,再使用map进行转换(x,sum),变换为Array
|
||||||
|
// 再使用sort针对sum进行排序,最后take前k个,再把数据变为x,y,z这种格式
|
||||||
|
nums.map((_, 1)).groupBy(_._1)
|
||||||
|
.map {
|
||||||
|
case (x, arr) => (x, arr.map(_._2).sum)
|
||||||
|
}
|
||||||
|
.toArray
|
||||||
|
.sortWith(_._2 > _._2)
|
||||||
|
.take(k)
|
||||||
|
.map(_._1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user