You are given an array of integers
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1 Output: [1]
Example 3:
Input: nums = [1,-1], k = 1 Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2 Output: [11]
Example 5:
Input: nums = [4,-2], k = 2 Output: [4]
Constraints:
1 <= nums.length <= 105 -104 <= nums[i] <= 104 1 <= k <= nums.length
Solution
這題難在邊界變換的時候,還要記錄當下的最大值
關鍵點在用一個 queue 來記錄window size 裡最大值的 index
當 queue 的第一個值等於 index-k,代表第一個值已經在窗外了,可以移除
因為這個 queue 是要記錄最大值的 index
所以每次都要檢查,當下的值,是不是比前面已經在 queue 裡指向的值大
是的話,就要移除 queue 裡的值
最後,因為每次移動 window,都要記錄目前的最大值
所以當 index 大於等於 k-1 的時候,就代表 window 已經滿足條件,可以開始紀錄最大值了
kotlin(參考解答)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun maxSlidingWindow(nums: IntArray, k: Int): IntArray { | |
val ans = arrayListOf<Int>() | |
val indexList = mutableListOf<Int>() | |
for(i in nums.indices) { | |
if(indexList.isNotEmpty() && indexList.first() == i - k) { | |
indexList.removeAt(0) | |
} | |
while(indexList.isNotEmpty() && nums[indexList.last()] < nums[i]) { | |
indexList.removeAt(indexList.lastIndex) | |
} | |
indexList.add(i) | |
if(i >= k-1) { | |
ans.add(nums[indexList.first()]) | |
} | |
} | |
return ans.toIntArray() | |
} | |
} |
沒有留言:
張貼留言