求滑动窗口的最大值
求滑动窗口中的最大值
public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length == 0){ return nums; } int[] results = new int[nums.length - k + 1]; int j = 0; Deque<Integer> deque = new ArrayDeque<>(); for(int i = 0; i < nums.length; i++){ if(i < k){ deque.offer(nums[i]); if(i == k - 1){ results[j] = max(deque); j++; } continue; } else{ while(deque.size() > 0 && nums[i] >= deque.peekLast()){ deque.pollLast(); } deque.offer(nums[i]); } results[j] = max(deque); j++; } return results; } private int max(Deque<Integer> deque) { if(deque.size() == 1){ return deque.peekLast(); } int max = 0; for (Integer data : deque) { if (data >= max) { max = data; } } return max; }