239. Sliding Window Maximum
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 class Solution { 2 public int[] maxSlidingWindow(int[] nums, int k) { 3 if (nums == null || k <= 0 || nums.length - k < 0) return new int[0]; 4 5 ArrayList<Integer> res = new ArrayList<>(); 6 // auxiliary queue that is sorted in descending order 7 Deque<Integer> q = new LinkedList<>(); 8 for (int i = 0; i < nums.length; i++) { 9 int data = nums[i]; 10 // enqueue. Remove those smaller values 11 while (!q.isEmpty() && q.getLast() < data) { 12 q.removeLast(); 13 } 14 q.add(data); 15 if (i < k - 1) continue; 16 // dequeue. If the current number is the maximum. Also remove it 17 // from the queue 18 res.add(q.getFirst()); 19 if (nums[i - k + 1] == q.getFirst()) { 20 q.removeFirst(); 21 } 22 } 23 return res.stream().mapToInt(i -> i).toArray(); 24 } 25 }

浙公网安备 33010602011771号