题解 | #最大矩形#

最大矩形

https://www.nowcoder.com/practice/5720efc1bdff4ca3a7dad37ca012cb60

做这题之前建议先去做力扣 84. 柱状图中最大的矩形,这题实际上是遍历每一行,以每一行为底形成一个柱状图, 柱状图中最大的矩形,然后取得最大值。

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix int整型二维数组
     * @return int整型
     */
     public int maximalRectangle(int[][] matrix) {
        int n = matrix.length, m = matrix[0].length;
        int[] height = new int[m];
        int maxArea=0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (matrix[i][j] == 1) height[j]++;
                else height[j] = 0;
            }
            maxArea=Math.max(maxArea,getMaxArea(height));
        }
        return maxArea;
    }

    public int getMaxArea(int[] height) {
        Deque<Integer> stack = new LinkedList<>();
        int[] newHeight = new int[height.length + 2];
        newHeight[0] = 0;
        newHeight[newHeight.length - 1] = 0;
        System.arraycopy(height, 0, newHeight, 1, height.length);
        stack.push(0);
        int maxArea=0;
        for (int i = 1; i < newHeight.length; i++) {
            if(newHeight[i]>=newHeight[stack.peek()]){
                stack.push(i);
            }else{
                while (!stack.isEmpty()&&newHeight[i]<newHeight[stack.peek()]){
                    int mid=stack.pop();
                    if(!stack.isEmpty()){
                        int left=stack.peek();
                        int area=(i-left-1)*newHeight[mid];
                        maxArea=Math.max(maxArea,area);
                    }
                }
                stack.push(i);
            }
        }
        return maxArea;
    }
}

全部评论

相关推荐

06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务