码迷,mamicode.com
首页 > Windows程序 > 详细

Sliding Window Maximum

时间:2016-07-20 06:37:48      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration from the start of the array, find the maximum number inside the window at each moving.

Example

For array [1, 2, 7, 7, 8], moving window size k = 3. return [7, 7, 8]

At first the window is at the start of the array like this

[|1, 2, 7| ,7, 8] , return the maximum 7;

then the window move one step forward.

[1, |2, 7 ,7|, 8], return the maximum 7;

then the window move one step forward again.

[1, 2, |7, 7, 8|], return the maximum 8;

Challenge 

o(n) time and O(k) memory

分析:

用LinkedList来保存window里的数,如果新加入的数比LinkedList的最后一个数大,我们可以把LinkedList里比那个新数小的都remove掉。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers.
 4      * @return: The maximum number inside the window at each moving.
 5      */
 6     public ArrayList<Integer> maxSlidingWindow(int[] A, int w) {
 7         
 8             // invalid input
 9          if (A == null || w <= 0 || A.length - w < 0) return new ArrayList<Integer>();
10          
11          ArrayList<Integer> B = new ArrayList<Integer>();
12          // auxiliary queue that is sorted in descending order
13          LinkedList<Integer> q = new LinkedList<Integer>();
14          for (int i = 0; i < A.length; i++) {
15              // enqueue. Remove those smaller values
16              int data = A[i];
17              while (!q.isEmpty() && q.getLast() < data) {
18                  q.removeLast();
19              }
20              q.add(data);
21              if (i < w - 1) continue; 
22              // dequeue. If the current number is the maximum. Also remove it
23              // from the queue
24              B.add(q.get(0));
25              if (A[i - w + 1] == q.getFirst()) {
26                  q.removeFirst();
27              }
28         }
29      //return new ArrayList<Integer>(Arrays.asList(B));
30      return B;
31     }
32 }

 

Sliding Window Maximum

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5686918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!