leetcode84. 柱状图中最大的矩形

思路一:

前一個柱子若大於後一個柱子,則它大於的部分其實對於後一個柱子後面的柱子與他形成的矩形大小沒有關係

基於此,每次遍歷回去更新,比較暴力,最後要優化一下全是同一高度的情況,即整個圖形爲一個矩形。

class Solution {
    public int largestRectangleArea(int[] heights) {
        int flag=0;
        for(int i=0;i<heights.length-1;i++){
            if(heights[i]==heights[i+1]){
                continue;
            }else{
                flag=1;
            }
        }
        if(flag==0){
            if(heights.length==0){
                return 0;
            }else{
                  return heights[0]*heights.length;
            }
          
        }
        int[]hei = new int[heights.length];
        int Max=0;
        for(int i = 0;i<heights.length;i++){
            hei[i]=heights[i];
            if(Max<heights[i]){
                Max=heights[i];
            }
            for(int j=i-1;j>=0;j--){
                if(hei[j]<=heights[i]){
                    if(hei[j]*(i-j+1)>Max){
                        Max = hei[j]*(i-j+1);
                    }
                }else{
                    hei[j] = heights[i];
                    if(hei[j]*(i-j+1)>Max){
                        Max=hei[j]*(i-j+1);
                    }
                }
                if(hei[j]>Max){
                    Max = hei[j];
                }
            }
        }
        return Max;
        
    }
}

思路二:

引用大佬的解釋(用棧 其實也用到上面那種方法的思想):

https://www.cnblogs.com/ganganloveu/p/4148303.html

自己的實現:

class Solution {
    public int largestRectangleArea(int[] heights) {
      Stack<Integer>stk =  new Stack<Integer>();
      int  Max=0;
      for(int i=0;i<heights.length;i++){
          if(stk.empty()){
              stk.push(heights[i]);
          }else{
              if(stk.peek()<=heights[i]){
                  stk.push(heights[i]);
              }else{
                  int count = 0 ;
                  while(!stk.empty()&&stk.peek()>heights[i]){
                      count++;
                      if(Max<count*stk.peek()){
                          Max = count*stk.pop();
                      }else{
                          stk.pop();
                      }
                  }
                  while(count>=0){
                      stk.push(heights[i]);
                      count--;
                  }
              }
          }
      }
         //System.out.print(Max);
      int len = stk.size();
      for(int i=1;i<=len;i++){
          if(stk.peek()*i>=Max){
              Max = stk.pop()*i;
              System.out.print(Max);
          }else{
              stk.pop();
          }
      }
         return Max;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值