leetcode Sliding Window Maximum

本文介绍了一种高效计算滑动窗口内最大值的方法,适用于数组操作和数据流处理场景。

A long array A[] is given to you. There is a sliding window of size w which is moving from the very left of the array to the very right. You can only see the wnumbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and w is 3.

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Input: A long array A[], and a window width w
Output: An array B[], B[i] is the maximum value of from A[i] to A[i+w-1]
Requirement: Find a good optimal way to get B[i]


// Type your Java code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).

public class Interpreter {
    public static void main(String[] args) {
        // Start typing your code here...
        int a[]={1,3,-1,-3,5,3,6,7};
        int b[]=new int[6];
        maxSlidingWindow(a,8,3,b);
        for(int i=0;i<6;i++)    System.out.println(b[i]);
    }
    public static void maxSlidingWindow(int a[],int n,int w,int b[]){
        if(n<=0||n<w) return;
        LinkedList<Integer> l=new LinkedList<Integer>();
        for(int i=0;i<w;i++){
            while(l.size()>0&&a[l.peekLast()]<=a[i]) l.pollLast();
            l.add(i);
        }
        b[0]=a[l.peekFirst()];
        for(int i=w;i<n;i++){
            while(l.size()>0&&l.peekFirst()<=i-w) l.removeFirst();
            while(l.size()>0&&a[l.peekLast()]<=a[i]) l.pollLast();
            l.add(i);
            b[i-w+1]=a[l.peekFirst()];
        }
        
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值