栈和队列题

1.生成窗口最大值。
这里写图片描述
两种方法:

//第一种:两个for循环,时间复杂度o(N*W)
    public static  LinkedList<Integer> getMaxWindow2(int[] arr,int w){
        if(arr==null||w<1||arr.length<w){
            return  null;
        }
        LinkedList<Integer> list = new LinkedList<>();
        int max=Integer.MIN_VALUE;
        for(int i=0;i<arr.length-w+1;i++){
            for(int j=i;j<i+w&&j<arr.length;j++){
                if(arr[j]>max){
                    max=arr[j];
                }
            }
            list.add(max);
            max=Integer.MIN_VALUE;
        }
        return  list;
    }
  //第二种,时间复杂度O(N)
     /**
     * 生成窗口最大值数组
     * 1.定义队列。2.遍历数组放于队尾,如果对尾元素小于将要放入的元素,进行出对操作。
     * 3.如果对尾的下标超过界限,将移除队头元素。4.将对首元素放于列表中。
     */
    public static  LinkedList<Integer> getMaxWindow(int[] arr,int w){
        if(arr==null||w<1||arr.length<w){
            return  null;
        }
        LinkedList<Integer> qmax= new LinkedList<>();
        LinkedList<Integer> list = new LinkedList<>();
        int index=0;
        for(int i=0;i<arr.length;i++){
            while (!qmax.isEmpty()&&arr[qmax.peekLast()]<=arr[i]){
                qmax.pollLast();
            }
            qmax.addLast(i);
            //队头的下标过期,窗口向右移动,对头如果过期将要删除
            if(qmax.peekFirst()==i-w){
                qmax.pollFirst();
            }
            if(i>=w-1){
               list.add(arr[qmax.peekFirst()]);
            }
        }
        return  list;
    } 

2.最大子矩阵的大小,例如:矩阵的高为3,2,3。最大子矩阵面经为2*3。

    /**
     * 求最大子矩阵的大小,时间复杂度为o(M*N)
     * 1.通过栈进行计算:从左到右遍历数组,每遍历一个位置,把位置放入栈中。栈中数据是由大到小排列,表示矩形可以向左边扩展。
     */
    public static int maxRecSize(int[] height){
        if(height==null||height.length==0){
            return  0;
        }
        int maxArea=0;
        Stack<Integer> stack = new Stack<>();
        for(int i=0;i<height.length;i++){
            while (!stack.isEmpty()&&height[i]<=height[stack.peek()]){
                int j=stack.pop();
                int k=stack.isEmpty()?-1:stack.peek();
                int cur=(i-k-1)*height[j];
                maxArea=Math.max(maxArea,cur);
            }
            stack.push(i);
        }
        while (!stack.isEmpty()){
            int j=stack.pop();
            int k=stack.isEmpty()?-1:stack.peek();
            int cur=(height.length-k-1)*height[j];
            maxArea=Math.max(maxArea,cur);
        }
        return  maxArea;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值