leetcode 85. Maximal Rectangle | 85. 最大矩形(单调栈)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 85. Maximal Rectangle | 85. 最大矩形(单调栈)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/maximal-rectangle/
題解
本題與 leetcode 84. Largest Rectangle in Histogram | 84. 柱狀圖中最大的矩形(單調(diào)棧) 思路相同,直接抄了原來的代碼。
也可參考之前的博客:左神算法:求最大子矩陣的大小(Java版)
另外,想到了另外一道類似但思路不同的題:221. Maximal Square
class Solution {public int maximalRectangle(char[][] matrix) {if (matrix.length == 0) return 0;int M = matrix.length;int N = matrix[0].length;int[][] heights = new int[M][N]; // 上方有多少個連續(xù)的1for (int i = 0; i < N; i++) {heights[0][i] = matrix[0][i] - '0';for (int j = 1; j < M; j++) {if (matrix[j][i] == '1') heights[j][i] = heights[j - 1][i] + 1;else heights[j][i] = 0;}}int result = 0;for (int i = 0; i < M; i++) {result = Math.max(largestRectangleArea(heights[i]), result);}return result;}// leetcode 84. Largest Rectangle in Histogrampublic int largestRectangleArea(int[] heights) {int L = heights.length;// 找左邊第一個小于h[i]的數(shù)// 從右向左遍歷,維護單調(diào)不減棧,小數(shù)h[i]不斷將大數(shù)h[j]彈出,則h[i]左邊第一個小于h[i]的數(shù)為h[j]Stack<Integer> valueStack = new Stack<>();Stack<Integer> indexStack = new Stack<>();int[] leftIndex = new int[L]; // i左邊第一個小于i的數(shù)的下標Arrays.fill(leftIndex, -1);for (int i = L - 1; i >= 0; i--) {while (!valueStack.isEmpty() && valueStack.peek() > heights[i]) {leftIndex[indexStack.pop()] = i;valueStack.pop();}valueStack.push(heights[i]);indexStack.push(i);}// 找右邊第一個小于h[i]的數(shù)// 從左向右遍歷,維護單調(diào)不減棧valueStack = new Stack<>();indexStack = new Stack<>();int[] rightIndex = new int[L]; // i右邊第一個小于i的數(shù)的下標Arrays.fill(rightIndex, L);for (int i = 0; i < L; i++) {while (!valueStack.isEmpty() && valueStack.peek() > heights[i]) {rightIndex[indexStack.pop()] = i;valueStack.pop();}valueStack.push(heights[i]);indexStack.push(i);}// 對于每個h[i],以其自身的高度,分別向左右擴張int maxArea = 0;for (int i = 0; i < L; i++) {maxArea = Math.max(maxArea, (rightIndex[i] - leftIndex[i] - 1) * heights[i]);}return maxArea;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 85. Maximal Rectangle | 85. 最大矩形(单调栈)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 84. Largest
- 下一篇: leetcode 978. Longes