LeetCode 239. Sliding Window Maximum(滑动窗口最大值)

314 阅读1分钟

leetcode.com/problems/sl…

Discuss:www.cnblogs.com/grandyang/p…

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

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

解法一:

可以使用优先队列来做,即最大堆,不过此时我们里面放一个 pair 对儿,由数字和其所在位置组成的,这样我们就可以知道每个数字的位置了,而不用再进行搜索了。在遍历每个数字时,进行 while 循环,假如优先队列中最大的数字此时不在窗口中了,就要移除,判断方法就是将队首元素的 pair 对儿中的 second(位置坐标)跟 i-k 对比,小于等于就移除。然后将当前数字和其位置组成 pair 对儿加入优先队列中。此时看若 i >= k-1,说明窗口大小正好是 k,就将最大值加入结果 res 中即可。

class Solution {
    fun maxSlidingWindow(nums: IntArray, k: Int): IntArray {
        val priorityQueue =
            PriorityQueue<Pair<Int, Int>>(Comparator<Pair<Int, Int>> { o1, o2 -> o2!!.first.compareTo(o1!!.first) })
        val result = mutableListOf<Int>()

        for (index in nums.indices) {
            while (priorityQueue.isNotEmpty() && priorityQueue.peek().second <= index - k) {
                priorityQueue.poll()
            }
            priorityQueue.offer(Pair(nums[index], index))
            if (index >= k - 1) {
                result.add(priorityQueue.peek().first)
            }
        }
        return result.toIntArray()
    }
}

解法二:

使用双向队列 deque 来解题,并提示我们窗口中只留下有用的值,没用的全移除掉。大概思路是用双向队列保存数字的下标,遍历整个数组,如果此时队列的首元素是 i-k 的话,表示此时窗口向右移了一步,则移除队首元素。然后比较队尾元素和将要进来的值,如果小的话就都移除,然后此时我们把队首元素加入结果中即可。

class Solution {
    fun maxSlidingWindow(nums: IntArray, k: Int): IntArray {
        val result = mutableListOf<Int>()

        val deque = ArrayDeque<Int>()

        for (i in nums.indices) {
            if (deque.isNotEmpty() && deque.first == i - k) {
                deque.removeFirst()
            }
            while (deque.isNotEmpty() && nums[deque.last] < nums[i]) {
                deque.removeLast()
            }
            deque.addLast(i)
            if (i >= k - 1) {
                result.add(nums[deque.first])
            }
        }
        return result.toIntArray()
    }
}