leetcode 239-Sliding Window Maximum(hard)
Posted yshi12
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 239-Sliding Window Maximum(hard)相关的知识,希望对你有一定的参考价值。
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
1. deque
use a deque to store the promising candidates for the max value in the sliding window. If the number is out of the bound of the window, then it can not be a candidate. If num[i] is inside the window, but num[i]<num[j], then nums[i] can not be a candidate, so we can delete it from deque. In this way, we can get a sorted decreasing deque, and the first element in the deque is the max value.
But, what should we store in deque, at first, I think of store the value of numbers, but how can we know whether the number is out of the sliding window? So we need to store the index of the number, and delete it when we find the index in the queue is out of the window. So, how do we get the value? It is saved in the number array.
注意,当存的是index的时候尤其要小心,很容易就会把index和value弄混,比如自己写的时候就把poll出的index直接当value用了。
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length==0) return new int[0]; Deque<Integer> dq=new ArrayDeque<>();//store index of nums offered to the deque int[] ans=new int[nums.length-k+1]; for(int i=0;i<nums.length;i++){ if(!dq.isEmpty()&&dq.peek()<i-k+1){ dq.poll(); } while(!dq.isEmpty()&&nums[dq.peekLast()]<nums[i]){ dq.pollLast(); } dq.offer(i); if(i>=k-1){ ans[i-k+1]=nums[dq.peek()]; } } return ans; } }
2. priorityqueue
use a priorityqueue to store the numbers inside the window, notice that for basic priorityqueue, the value is increasing, but here, we need it to be decreasing, so we need to add a comparator.
comparator写的太少,需要多练习多巩固,记清楚该怎么写,匿名函数该怎么写。
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length==0) return new int[0]; int[] ans=new int[nums.length-k+1]; PriorityQueue<Integer> pq=new PriorityQueue<>(k,new Comparator<Integer>(){ @Override public int compare(Integer i1, Integer i2){ return Integer.compare(i2,i1); } }); for(int i=0;i<k;i++){ pq.offer(nums[i]); } for(int i=k-1;i<nums.length;i++){ if(i>k-1){ pq.remove((Integer)nums[i-k]); pq.offer((Integer)nums[i]); } ans[i-k+1]=pq.peek(); } return ans; } }
以上是关于leetcode 239-Sliding Window Maximum(hard)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 239-Sliding Window Maximum(hard)
[leetcode]239. Sliding Window Maximum滑动窗口最大值
leetcode-hard-array-239. Sliding Window Maximum