zoukankan      html  css  js  c++  java
  • LeetCode最小栈总结

    962.最大宽度

    题目:

    给定一个整数数组 A,坡是元组 (i, j),其中  i < j 且 A[i] <= A[j]。这样的坡的宽度为 j - i。
    找出 A 中的坡的最大宽度,如果不存在,返回 0 。
     1 class Solution {
     2    public int maxWidthRamp(int[] A) {
     3     Deque<Integer> stack=new ArrayDeque<>();
     4     int res=0;
     5     for(int i=0;i<A.length;i++){
     6         if(stack.isEmpty() || A[stack.peek()]>A[i]){
     7             stack.push(i);
     8         }
     9     }
    10     for(int i=A.length-1;i>=0;i--){
    11         while(!stack.isEmpty() && A[stack.peek()]<=A[i]){
    12             int cur=stack.pop();
    13             res=Math.max(res,i-cur);
    14         }
    15     }
    16     return res;
    17 }
    18 
    19 
    20 }

    1124.表现良好的时间段

    题目:

    给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
    我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
    所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
    请你返回「表现良好时间段」的最大长度。
     
     
     
    分析:这里的题意可以转化成上题,即
    给定一个整数数组 A,连续每天干活时长是元组 (i, j),其中  i < j 且 A[i] < A[j]。这样表现良好的时间段为j -i,
    找出 A 中表现良好的时间段,如果不存在,返回 0 。
     
    class Solution {
        public int longestWPI(int[] A) {
       Deque<Integer> stack=new ArrayDeque<>();
        int res=0;
    
        for(int i = 0; i < A.length; i ++){
            A[i] = A[i] > 8 ?  1:-1;
        }
        int[] preSum = new int[A.length+1];
        preSum[0] = 0;
        for(int i = 1; i <= A.length; i ++){
            preSum[i] = preSum[i-1]+A[i-1];
        }
        for(int i=0;i<preSum.length;i++){
            if(stack.isEmpty() || preSum[stack.peek()]>preSum[i]){
                stack.push(i);
            }
        }
        for(int i=preSum.length-1;i>=0;i--){
            while(!stack.isEmpty() && preSum[stack.peek()]<preSum[i]){
                int cur=stack.pop();
                res=Math.max(res,i-cur);
            }
        }
        return res;
           
    
        }
    }
     
     
     
  • 相关阅读:
    kali linux DDos攻击
    js基础接替上回的作用域
    js基础的知识函数和作用域
    写作是最好的思考
    eclipse 常用操作(转载)
    网页中用jquery validate 验证表单输入项
    eclipse5.5添加反编译插件
    velocity 实现td 中月份的多选框
    LinckedhashMap原理
    api服务端接口安全
  • 原文地址:https://www.cnblogs.com/moonyaoo/p/13022636.html
Copyright © 2011-2022 走看看