239. Sliding Window Maximum

Description

Given an array 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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

239. Sliding Window Maximum_第1张图片
window

Therefore, return the max sliding window as [3,3,5,5,6,7].

**Note: **
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

Solution

PriorityQueue, time O(n), space O(k)

有点LRU Cache的感觉。先进先出!

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 1) {
            return nums;
        }
        
        PriorityQueue queue 
            = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        
        for (int i = 0; i < k - 1; ++i) {
            // decide if nums[i] is better than queue.peek()
            while (!queue.isEmpty() && nums[i] >= queue.peek()[1]) {
                queue.poll();
            }
            queue.offer(new int[]{i, nums[i]});
        }
        
        int[] max = new int[nums.length - k + 1];
        
        for (int i = k - 1; i < nums.length; ++i) {
            while (!queue.isEmpty() 
                   && (nums[i] >= queue.peek()[1] || queue.peek()[0] < i - k + 1)) {
                queue.poll();
            }
            queue.offer(new int[]{i, nums[i]});
            
            max[i - k + 1] = queue.peek()[1];
        }
        
        return max;
    }
}

你可能感兴趣的:(239. Sliding Window Maximum)