239. Sliding Window Maximum
用Dequeue
1 class Solution { 2 public int[] maxSlidingWindow(int[] nums, int k) { 3 if(nums.length == 0 || nums.length < k) return new int[0]; 4 int[] res = new int[nums.length - k + 1]; 5 Deque<Integer> deque = new LinkedList<>(); 6 for(int i = 0; i < nums.length; i++){ 7 if(!deque.isEmpty() && deque.peek() < i - k + 1){ 8 deque.poll(); 9 } 10 while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]){ 11 deque.pollLast(); 12 } 13 deque.offer(i); 14 if(i >= k-1){ 15 res[i - k + 1] = nums[deque.peek()]; 16 } 17 } 18 return res; 19 20 } 21 } 22 23 24 25 26 //O(n^2) 27 class Solution { 28 public int[] maxSlidingWindow(int[] nums, int k) { 29 int[] res = new int[nums.length-k+1]; 30 if(nums.length == 0 || nums.length < k) return new int[]{}; 31 int begin = 0, end = k-1; 32 int max = Integer.MIN_VALUE; 33 for(int i = begin; i <= end; i++){ 34 max = Math.max(nums[i], max); 35 } 36 res[begin] = max; 37 begin++; 38 end++; 39 while(end < nums.length){ 40 res[begin] = Integer.MIN_VALUE; 41 for(int i = begin; i <= end; i++){ 42 res[begin] = Math.max(res[begin], nums[i]); 43 } 44 begin++; 45 end++; 46 } 47 return res; 48 49 } 50 }