Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 748a728

Browse files
committed
添加 0239.滑动窗口最大值.md Scala版本
1 parent 8c394c9 commit 748a728

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎problems/0239.滑动窗口最大值.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,53 @@ func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
630630
return result
631631
}
632632
```
633+
Scala:
634+
```scala
635+
import scala.collection.mutable.ArrayBuffer
636+
object Solution {
637+
def maxSlidingWindow(nums: Array[Int], k: Int): Array[Int] = {
638+
var len = nums.length - k + 1 // 滑动窗口长度
639+
var res: Array[Int] = new Array[Int](len) // 声明存储结果的数组
640+
var index = 0 // 结果数组指针
641+
val queue: MyQueue = new MyQueue // 自定义队列
642+
// 将前k个添加到queue
643+
for (i <- 0 until k) {
644+
queue.add(nums(i))
645+
}
646+
res(index) = queue.peek // 第一个滑动窗口的最大值
647+
index += 1
648+
for (i <- k until nums.length) {
649+
queue.poll(nums(i - k)) // 首先移除第i-k个元素
650+
queue.add(nums(i)) // 添加当前数字到队列
651+
res(index) = queue.peek() // 赋值
652+
index+=1
653+
}
654+
// 最终返回res,return关键字可以省略
655+
res
656+
}
633657

658+
}
659+
660+
class MyQueue {
661+
var queue = ArrayBuffer[Int]()
662+
663+
// 移除元素,如果传递进来的跟队头相等,那么移除
664+
def poll(value: Int): Unit = {
665+
if (!queue.isEmpty && queue.head == value) {
666+
queue.remove(0)
667+
}
668+
}
669+
670+
// 添加元素,当队尾大于当前元素就删除
671+
def add(value: Int): Unit = {
672+
while (!queue.isEmpty && value > queue.last) {
673+
queue.remove(queue.length - 1)
674+
}
675+
queue.append(value)
676+
}
677+
678+
def peek(): Int = queue.head
679+
}
680+
```
634681
-----------------------
635682
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /