一:题目
二:思路
1:lc通过版
class Solution {public int[] maxSlidingWindow(int[] nums, int k) {if (nums.length == 1) return nums;MyQueue queue = new MyQueue();int len = nums.length - k + 1;int[] ans = new int[len];int index = 0;for (int i = 0; i < k; i++) {queue.add(nums[i]);}ans[index++] = queue.peek();for (int i = k; i < nums.length; i++) {queue.poll(nums[i-k]);queue.add(nums[i]);ans[index++] = queue.peek();}return ans;}
}class MyQueue{Deque<Integer> deque = new LinkedList<>();public void poll(int val) {if (!deque.isEmpty() && deque.peek() == val) {deque.poll();}} public void add(int val) {while (!deque.isEmpty() && val > deque.getLast()) {deque.removeLast();} deque.add(val);}public int peek() { return deque.peek();}}
2:lc超时版
class Solution {public int max(int[] segment,int n) {int maxx = -999999;for (int i = 0; i < n; i++) {if (maxx < segment[i]) {maxx = segment[i];}}return maxx;}public int[] maxSlidingWindow(int[] nums, int k) {int len = nums.length-k+1;int[] ans = new int[len];int ansIndex = 0;for (int i = 0; i < len; i++) {int[] temp = new int[k];int tempIndex = 0;int count = 0;int j = i;while (count != k) {temp[tempIndex++] = nums[j++];count++;}int eachAns = max(temp,k);ans[ansIndex++] = eachAns;}return ans;}
}