前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode85. 最大矩形

LeetCode85. 最大矩形

作者头像
mathor
发布2018-08-17 15:39:05
1.5K0
发布2018-08-17 15:39:05
举报
文章被收录于专栏:mathor
题目链接:LeetCode85

 这是LeetCode84题的一个扩展。这道题做法和84很类似,首先对第一行求一个最大体积,然后到第二行,将第一行的值累加到第二行上,但是有一个前提条件,如果第二行某一列的值是0,那就直接是0了,比方说第二行累加后的值为2,0,2,1,1,然后对这个值求一次最大体积。第三行累加后的值为3,1,3,2,2,第四行累加后的值为4,0,0,3,0

代码语言:javascript
复制
class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int maxArea = 0;
        int[] height = new int[matrix[0].length];
        for(int i = 0;i < matrix.length;i++) {
            for(int j = 0;j < matrix[0].length;j++) {
                height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;
            }
            maxArea = Math.max(maxArea,largestRectangleArea(height));
        }
        return maxArea;
    }
    public static int largestRectangleArea(int[] heights) {
        if(heights == null || heights.length == 0)
            return 0;
        int maxArea = 0;
        Stack<Integer> stack = new Stack<Integer>();//从栈底到栈顶依次增大
        for(int i = 0;i < heights.length;i++) {//遍历数组
            while(!stack.isEmpty() && heights[i] <= heights[stack.peek()]) {
                //栈不为空并且当前值小于等于栈顶元素
                int j = stack.pop();//出栈
                int k = stack.isEmpty() ? -1 : stack.peek();
                int curArea = (i - k - 1) * heights[j];//底×高
                maxArea = Math.max(maxArea,curArea);//找最大值
            }
            stack.push(i);//i进栈
        }
        while(!stack.isEmpty()) {
            //数组遍历完了,栈内还有值
            int j = stack.pop();
            int k = stack.isEmpty() ? -1 : stack.peek();
            int curArea = (heights.length - k - 1) * heights[j];
            maxArea = Math.max(maxArea,curArea);
        }
        return maxArea;
    }
}

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-08-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:LeetCode85
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档