leetcode 239-Sliding Window Maximum(hard)

2021-07-08 10:06

阅读:462

标签:ast   就会   nbsp   匿名函数   dex   tor   turn   imu   only   

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]

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 dq=new ArrayDeque();//store index of nums offered to the deque
        int[] ans=new int[nums.length-k+1];
        for(int i=0;i){
            if(!dq.isEmpty()&&dq.peek()){
                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 pq=new PriorityQueue(k,new Comparator(){
            @Override
            public int compare(Integer i1, Integer i2){
                return Integer.compare(i2,i1);
            }
        });
        for(int i=0;i){
            pq.offer(nums[i]);
        }
        for(int i=k-1;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)

标签:ast   就会   nbsp   匿名函数   dex   tor   turn   imu   only   

原文地址:https://www.cnblogs.com/yshi12/p/9739780.html


评论


亲,登录后才可以留言!