方法一:
这道题跟左神上课讲的题一样,可以使用一个双端队列来对存数据。
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int[] list=new int[nums.length-k+1]; LinkedList<Integer> deque=new LinkedList<>(); int index=0; for(int i=0;i<nums.length;i++){ while(!deque.isEmpty()&&nums[deque.peekLast()]<=nums[i]){ deque.pollLast(); } deque.add(i); if(i-deque.peekFirst()==k){ deque.pollFirst(); } if(i>=k-1){ list[index++]=nums[deque.peekFirst()]; } } return list; } }
方法二:动态规划(官方给出的解答)
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; if (n * k == 0) return new int[0]; if (k == 1) return nums; int [] left = new int[n]; left[0] = nums[0]; int [] right = new int[n]; right[n - 1] = nums[n - 1]; for (int i = 1; i < n; i++) { // from left to right if (i % k == 0) left[i] = nums[i]; // block_start else left[i] = Math.max(left[i - 1], nums[i]); // from right to left int j = n - i - 1; if ((j + 1) % k == 0) right[j] = nums[j]; // block_end else right[j] = Math.max(right[j + 1], nums[j]); } int [] output = new int[n - k + 1]; for (int i = 0; i < n - k + 1; i++) output[i] = Math.max(left[i + k - 1], right[i]); return output; } }