leetcode85.最大矩形
leetcode85.最大矩形
题目
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
用例
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
输入:matrix = []
输出:0
输入:matrix = [["0"]]
输出:0
输入:matrix = [["1"]]
输出:1
输入:matrix = [["0","0"]]
输出:0
求解
/**
* @param {character[][]} matrix
* @return {number}
*/
var maximalRectangle = function(matrix) {
let max_Area = 0
for(let i=0;i<matrix.length;i++){
let heights = []
for(j=0;j<matrix[0].length;j++){
let height = 0
let p=i;
while(p>=0){
if(matrix[p][j]==0){
break
}
height++
p--
}
heights.push(height)
}
let tmp = largestArea(heights)
tmp>max_Area?max_Area=tmp:max_Area=max_Area
}
return max_Area
function largestArea(heights){
let height_stack = []
let index_stack = []
let maxArea = 0
//哨兵
heights[heights.length]=0
height_stack.push(heights[0])
index_stack.push(0)
let final_index = 0
let flag = false
let i =1
while(i<heights.length){
//如果第i个柱子高度要严格小于栈顶元素,那么以栈顶元素为高的矩阵可以计算出其高度
if(heights[i]<height_stack[height_stack.length-1]){
flag=true
//出栈
let height = height_stack[height_stack.length-1]
height_stack.pop()
let index = index_stack[index_stack.length-1]
final_index =index
index_stack.pop()
//计算宽度
let weight = i-index
weight*height>maxArea?maxArea=weight*height:maxArea=maxArea
}else if(heights[i]==height_stack[height_stack.length-1]){
flag=false
//相等的情况直接无视
i++
}else{
//入栈
//如果是出栈以后的入栈
if(flag==true){
height_stack.push(heights[i])
index_stack.push(final_index)
flag=false
}else{
height_stack.push(heights[i])
index_stack.push(i)
}
i++
}
}
return maxArea
}
};

浙公网安备 33010602011771号