添加 0239.滑动窗口最大值.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-17 18:41:52 +08:00
parent 8c394c9f85
commit 748a728420

View File

@ -630,6 +630,53 @@ func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
return result
}
```
Scala:
```scala
import scala.collection.mutable.ArrayBuffer
object Solution {
def maxSlidingWindow(nums: Array[Int], k: Int): Array[Int] = {
var len = nums.length - k + 1 // 滑动窗口长度
var res: Array[Int] = new Array[Int](len) // 声明存储结果的数组
var index = 0 // 结果数组指针
val queue: MyQueue = new MyQueue // 自定义队列
// 将前k个添加到queue
for (i <- 0 until k) {
queue.add(nums(i))
}
res(index) = queue.peek // 第一个滑动窗口的最大值
index += 1
for (i <- k until nums.length) {
queue.poll(nums(i - k)) // 首先移除第i-k个元素
queue.add(nums(i)) // 添加当前数字到队列
res(index) = queue.peek() // 赋值
index+=1
}
// 最终返回resreturn关键字可以省略
res
}
}
class MyQueue {
var queue = ArrayBuffer[Int]()
// 移除元素,如果传递进来的跟队头相等,那么移除
def poll(value: Int): Unit = {
if (!queue.isEmpty && queue.head == value) {
queue.remove(0)
}
}
// 添加元素,当队尾大于当前元素就删除
def add(value: Int): Unit = {
while (!queue.isEmpty && value > queue.last) {
queue.remove(queue.length - 1)
}
queue.append(value)
}
def peek(): Int = queue.head
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>