码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 84--柱状图中最大的矩形( Largest Rectangle in Histogram) 85--最大矩形(Maximal Rectangle)

时间:2019-09-23 22:29:39      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:histogram   height   strong   for   ||   blog   ges   -o   term   

84题和85五题 基本是一样的,先说84题

84--柱状图中最大的矩形( Largest Rectangle in Histogram)

技术图片
思路很简单,通过循环,分别判断第 i 个柱子能够延展的长度len,最后把len*heights[i] 就是延展开的面积,最后做比对,得出最大。

    public int largestRectangleArea(int[] heights) {
        int ans=0;
        for(int i=0;i<heights.length;i++) {
                int len=1,left=i,right=i;
                while(left>0&&heights[--left]>=heights[i]) len++;//向左延展
                while(right<heights.length-1&&heights[++right]>=heights[i]) len++; //向右延展
                ans=Math.max(ans,heights[i]*len); //更新最大值
        }
        return ans;
    }

这个方法效率不是很高,但是是最简单,也是最容易理解的。、

85--最大矩形(Maximal Rectangle)

这一题的思路与上一题相同。主要是第一步。
首先我们先建立一个大小和Matrix相同的大小的二维数组map

        int Y=matrix.length;
        int X=matrix[0].length;
        int[][] map=new int[Y][X];
        for(int y=0;y<Y;y++) {
            for(int x=0;x<X;x++) {
                if(matrix[y][x]=='1') {
                /*假如matrix[y][x]=='1',就把当前位置的map值,加上map[y-1][x]的值,如
                000       000
                111  -》 111
                101       202*/
                    if(y>0) {
                        map[y][x]=map[y-1][x]+1;
                    }else {
                        map[y][x]=1;
                    }
                }
            }
        }

通过向下累加的方式,更新map,然后在对每一行的map[y],进行如84题的操作,就可以得出最大的面积

    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0||matrix[0].length==0) return 0;
        int Y=matrix.length;
        int X=matrix[0].length;
        int[][] map=new int[Y][X];
        for(int y=0;y<Y;y++) {
            for(int x=0;x<X;x++) {
                if(matrix[y][x]=='1') {
                    if(y>0) {
                        map[y][x]=map[y-1][x]+1;
                    }else {
                        map[y][x]=1;
                    }
                }
            }
        }
        int ans=0;
        //这里和84题一样
        for(int[] nums:map) {
            for(int i=0;i<nums.length;i++) {
                int len=1,left=i,right=i;
                while(left>0&&nums[--left]>=nums[i]) len++;
                while(right<nums.length-1&&nums[++right]>=nums[i]) len++;
                ans=Math.max(ans,nums[i]*len);
            }
        }
        return ans;
    }

就是这样

LeetCode 84--柱状图中最大的矩形( Largest Rectangle in Histogram) 85--最大矩形(Maximal Rectangle)

标签:histogram   height   strong   for   ||   blog   ges   -o   term   

原文地址:https://www.cnblogs.com/duangL/p/11575114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!