單調棧的應用

  • 可以解決 求數組元素左邊第一個大於其的元素
  • 接雨水 leetcode 42

給定 n 個非負整數表示每個寬度爲 1 的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度圖,在這種情況下,可以接 6 個單位的雨水(藍色部分表示雨水)
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/trapping-rain-water
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

    private int res = 0;
   public int trap(int[] height) {
       if(height.length == 0||height.length == 1||height.length == 2){
           return 0;
       }
       LinkedList<Integer> stack = new LinkedList<>();
       for(int i = 0;i<height.length;i++){
           int val = height[i];
           
           while(!stack.isEmpty() && val>height[stack.peek()]){
               int curIdex = stack.peek();
               //彈出棧頂元素 若棧頂有多個相等對應值的元素 都彈出
               while(!stack.isEmpty()&&height[curIdex] == height[stack.peek()]){
                   stack.pop();
               }
               if(!stack.isEmpty()){
                    int h = Math.min(val,height[stack.peek()]) - height[curIdex];
                    int w = i - stack.peek()-1;
                    res += h*w;
               }
               
           }
           stack.push(i);
           
       }
       return res;
    }
  • leetcode 84

給定 n 個非負整數,用來表示柱狀圖中各個柱子的高度。每個柱子彼此相鄰,且寬度爲 1 。
求在該柱狀圖中,能夠勾勒出來的矩形的最大面積。

    private int max = Integer.MIN_VALUE;
    public int largestRectangleArea(int[] heights) {
        if(heights== null || heights.length == 0){
            return 0;
        }
        int[] leftSide = new int[heights.length];
        int[] rightSide = new int[heights.length];
        LinkedList<Integer> stack = new LinkedList<>();
        stack.push(-1);
        for(int i = 0;i<heights.length;i++){
            int tem =0;
            int val = heights[i];
            while((tem =stack.peek())>=0){
                if(heights[tem] >= val){
                    stack.pop();
                }else{
                    leftSide[i] = tem;
                    stack.push(i);
                    break;
                }
            }
            if(tem <0){
                leftSide[i] = tem;
                stack.push(i);
            }      
        }
        stack = new LinkedList<>();
        stack.push(heights.length);
        for(int i = heights.length -1;i>=0;i--){
            int tem =heights.length;
            int val = heights[i];
            while((tem =stack.peek())<heights.length){
                if(heights[tem] >= val){
                    stack.pop();
                }else{
                    rightSide[i] = tem;
                    stack.push(i);
                    break;
                }
            }
            if(tem >=heights.length){
                stack.push(i);
                rightSide[i] = tem;
            }      
        }
        for(int  i = 0;i<heights.length;i++){
            max = Math.max(max,heights[i]*(rightSide[i]-leftSide[i]-1));
        }
        return max;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章