标签:
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.
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
;
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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5686918.html