239. Sliding Window Maximum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了239. Sliding Window Maximum相关的知识,希望对你有一定的参考价值。

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.

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
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 arrays size for non-empty array.

Follow up:
Could you solve it in linear time?

方法一:Heap时间 O(NlogK) 空间 O(K)

maintain a maximum heap, notice PriorityQueue.remove(object o) can remove certain object from our heap.

When writting Maximum Heap, be sure to define a comparator and override its compare function. The default one is Minimum Heap.

But this is not in linear time

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums == null || nums.length == 0) return new int[0];
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
        int[] res = new int[nums.length + 1 - k];
      index = 0;
        for(int i = 0; i < nums.length; i++){
            // 把窗口最左边的数去掉
            if(i >= k) pq.remove(nums[i - k]);
            // 把新的数加入窗口的堆中
            pq.offer(nums[i]);
            // 堆顶就是窗口的最大值
            if(i >= k - 1) res[index++] = pq.peek();
        }
        return res;
    }
}

  

方法二:https://segmentfault.com/a/1190000003903509

双向队列

复杂度

时间 O(N) 空间 O(K)

思路--双向队列作为窗口,

1.可以保证窗口的size---此处不能直接用size, 因为题目要求窗口内元素连续, 而此处不断pop()不满足题意, 所以要看坐标是否满足题意.

2. 可以保证队列有序, 跟stack 差不多, 保证相对顺序不变但是按要求出栈, 只留下递增或者递减的元素

我们用双向队列可以在O(N)时间内解决这题。当我们遇到新的数时,将新的数和双向队列的末尾比较,如果末尾比新数小,则把末尾扔掉,直到该队列的末尾比新数大或者队列为空的时候才住手。这样,我们可以保证队列里的元素是从头到尾降序的,由于队列里只有窗口内的数,所以他们其实就是窗口内第一大,第二大,第三大...的数。保持队列里只有窗口内数的方法和上个解法一样,也是每来一个新的把窗口最左边的扔掉,然后把新的加进去。然而由于我们在加新数的时候,已经把很多没用的数给扔了,这样队列头部的数并不一定是窗口最左边的数。这里的技巧是,我们队列中存的是那个数在原数组中的下标,这样我们既可以直到这个数的值,也可以知道该数是不是窗口最左边的数。这里为什么时间复杂度是O(N)呢?因为每个数只可能被操作最多两次,一次是加入队列的时候,一次是因为有别的更大数在后面,所以被扔掉,或者因为出了窗口而被扔掉。

Java 里面 Deque是个interface, ArrayDeque, LinkedList都implement了这个interface

所以可以这样定义

Deque<Integer> q = new ArrayDeque<Integer>();

Deque<Integer> q = new LinkedList<Integer>();

有peek(), peekFirst(), peekLast(), poll(), pollLast()等方法

public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums==null || nums.length==0) return new int[0];
        int[] res = new int[nums.length-k+1];
        int index = 0;
        LinkedList<Integer> deque = new LinkedList<Integer>();
        for (int i=0; i<nums.length; i++) {
            // 每当新数进来时,如果发现队列头部的数的下标,是窗口最左边数的下标,则扔掉
            if (!deque.isEmpty() && deque.peekFirst() == i-k) deque.removeFirst();
            
            // 把队列尾部所有比新数小的都扔掉,保证队列是降序的
            while (!deque.isEmpty() && nums[deque.peekLast()]<nums[i]) {
                deque.removeLast();
            }
            // 加入新数
            deque.offerLast(i);
            
            // 队列头部就是该窗口内第一大的
            if (i >= k-1) res[index++] = nums[deque.peekFirst()];
        }
        return res;
    }
}

  

好方法之二(好懂一些): 再转一个同样思路的算法:(deque里面放的是可能成为window里面max number的promising candidates, 一旦不可能,就要删掉,比如下面2那种情况)

另外一点是:deque里面不仅是降序排列这种关系,同时也是被移出窗口时间早晚的关系, 所以deque里面最左边的元素可以被理解为我们关注的promising element里面最早被移除的

We scan the array from 0 to n-1, keep "promising" elements in the deque. The algorithm is amortized O(n) as each element is put and polled once.

At each i, we keep "promising" elements, which are potentially max number in window [i-(k-1),i] or any subsequent window. This means

  1. If an element in the deque and it is out of i-(k-1), we discard them. We just need to poll from the head, as we are using a deque and elements are ordered as the sequence in the array

  2. Now only those elements within [i-(k-1),i] are in the deque. We then discard elements smaller than a[i] from the tail. This is because if a[x] <a[i] and x<i, then a[x] has no chance to be the "max" in [i-(k-1),i], or any other subsequent window: a[i] would always be a better candidate.

  3. As a result elements in the deque are ordered in both sequence in array and their value. At each step the head of the deque is the max element in [i-(k-1),i]

public class Solution {
    public int[] maxSlidingWindow(int[] a, int k) {        
            if (a == null || k <= 0) {
                return new int[0];
            }
            int n = a.length;
            int[] r = new int[n-k+1];
            int ri = 0;
            // store index
            Deque<Integer> q = new LinkedList<>();
            for (int i = 0; i < a.length; i++) {
                // remove numbers out of range k
                while (!q.isEmpty() && q.peek() <= i - k) {
                    q.poll();
                }
                // remove smaller numbers in k range as they are useless,  < or <= both are OK
                while (!q.isEmpty() && a[q.peekLast()] <= a[i]) {
                    q.pollLast();
                }
                // q contains index... r contains content
                q.offer(i);
                if (i >= k - 1) {
                    r[ri++] = a[q.peek()];
                }
            }
            return r;
        }
}

  

以上是关于239. Sliding Window Maximum的主要内容,如果未能解决你的问题,请参考以下文章

239. Sliding Window Maximum

239.Sliding Window Maximum

leetcode 239. Sliding Window Maximum

leetcode_239. 滑动窗口最大值

239. Sliding Window Maximum

239. Sliding Window Maximum