剑指 Offer 59 - I. 滑动窗口的最大值

import java.util.ArrayDeque;
import java.util.Deque;

/*
 * @lc app=leetcode.cn id=239 lang=java
 *
 * [239] 滑动窗口最大值
 */

// @lc code=start
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || k == 0) return new int[0];
        int n = nums.length;
        int[] res = new int[n - k + 1];
        int idx = 0;

        Deque<Integer> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            while (!q.isEmpty() && q.peekFirst() < i - k + 1)
                q.pollFirst();
            while (!q.isEmpty() && nums[i] >= nums[q.peekLast()])
                q.pollLast();
            q.addLast(i);
            if (i >= k - 1) {
                res[idx++] = nums[q.peekFirst()];
            }
        }
        
        return res;
    }
}
// @lc code=end

posted @ 2021-09-06 17:12  Dazzling!  阅读(25)  评论(0编辑  收藏  举报