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

Follow up:
Could you solve it in linear time?

 

本题和570第一次月考的一道题目很类似,用到的知识是amortized,方法与下面的题目的题干比较类似,不过是求最大值,还有就是不用回收小于某一值的数组。

An ordered stack is a singly linked list data structure that stores a sequence of items in increasing order. The head of the list always contains the smallest item in the list. The ordered stack supports the following two operations. POP() deletes and returns the head (NULL if there are no elements in the list). PUSH(x) removes all items smaller than x from the beginning of the list, adds x and then adds back all previously removed items. PUSH and POP can only access items in the list starting with the head. What would be the amortized cost of PUSH operation, if we start with an empty
list?? Use the aggregate method. 
Solution: The worst sequence of operations is pushing in order. Assume we push 1,2,3, ..., n, starting with an empty list. The first push costs 1. The second push costs 3 (pop, push(2), push(1)). The last push costs 2n-1 ( n-1 pops followed by push(n), followed by n-1 pushes). The total cost is given by 1 + 3 + 5 + ... +(2n-1) = O(n2)
The amortized cost is O(n)
 
代码如下:
 1 public class Solution {
 2     public int[] maxSlidingWindow(int[] nums, int k) {
 3         if(nums.length==0||k==0) return new int[0];
 4         Deque<Integer> q = new ArrayDeque<>();
 5         int[] res = new int[nums.length-k+1];
 6         int ri = 0;
 7         for(int i=0;i<nums.length;i++){
 8             while(!q.isEmpty()&&i-q.peek()>k-1){
 9                 q.poll();
10             }
11             while(!q.isEmpty()&&nums[q.peekLast()]<nums[i]){
12                 q.pollLast();
13             }
14             q.offer(i);
15             if(i-k+1>=0){
16                 res[ri++] = nums[q.peek()];
17             }
18         }
19         return res;
20     }
21 }

ArrayDeque有几个方法需要掌握,如下:poll,pollLast,peek,peekLast,offer,add;

posted @ 2017-03-04 07:59  CodesKiller  阅读(152)  评论(0编辑  收藏  举报