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;
    }
}

 

转载于:https://www.cnblogs.com/yshi12/p/9739780.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值