生成窗口最大值数组

这里写图片描述
这里写图片描述
代码实现:

package com.lyf.stack;

import java.util.LinkedList;

/**
 * Created by fangjiejie on 2017/5/10.
 */
public class WindowMaxValue {
    public static void main(String[] args) {
        int a[]={4,3,5,4,3,3,6,7};
        int b[]=getResult(a,3);
        for(int i:b){
            System.out.print(i+",");
        }
    }
    public static int[] getResult(int []arr,int s){//值得说明的是,我们进出队列的是数组下标,以此作为标记
        if(arr==null&&arr.length<s&&s<1){//把异常情况排除
            return  null;
        }
        int []result=new int[arr.length-s+1];
        LinkedList<Integer> list=new LinkedList<>();
        int index=0;
        for(int i=0;i<arr.length;i++){
            while(!list.isEmpty()&&arr[list.peekFirst()]<=arr[i]){//如果新要添加的值比末尾保留值大,末尾保留值则无用剔除,
                list.pollLast();
            }
            list.add(i);//整个队列始终保持着以队首最大的降序序列
            if(list.peekFirst()==i-s){//如果队首值过期,也就是队首已经不再窗口范围内,就把它剔除
                list.pollFirst();
            }
            if(i>=s-1){
                result[index++]=arr[list.peekFirst()];//队首为最大值
            }
        }
        return result;
    }
}

上面的代码据说有问题,已更改如下,感谢批评!

    public ArrayList<Integer> getMaxValues(int a[],int w){
        int n=a.length;
        int result[]=new int[n];
        int count=0;
        LinkedList<Integer> list=new LinkedList<>();
        ArrayList<Integer> maxArray=new ArrayList<>();
        for(int i=0;i<n;i++){
            while (!list.isEmpty()&&a[i]>a[list.peek()]){
                list.pop();
            }
            list.push(i);
            if(i>=2){
                while (!list.isEmpty()&&list.getLast()<i-2) {
                    System.out.print(a[list.getLast()]+"----");
                    list.removeLast();
                }
                maxArray.add(a[list.getLast()]);
            }

            Iterator<Integer> it=list.iterator();
            while (it.hasNext()){
                System.out.print(a[it.next()]+";");
            }
            System.out.println();
        }
        return maxArray;
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值