@@ -630,6 +630,53 @@ func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
630
630
return result
631
631
}
632
632
```
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
+ }
633
657
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
+ ```
634
681
-----------------------
635
682
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img ></div >
0 commit comments