leetcode 1504. Count Submatrices With All Ones | 1504. 统计全 1 子矩形(单调栈)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 1504. Count Submatrices With All Ones | 1504. 统计全 1 子矩形(单调栈)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/count-submatrices-with-all-ones/
題解
本題與 leetcode 84. Largest Rectangle in Histogram | 84. 柱狀圖中最大的矩形(單調棧) 思路相似,借鑒了原來的代碼。
以及類似問題:leetcode 85. Maximal Rectangle | 85. 最大矩形(單調棧)
class Solution {public int numSubmat(int[][] mat) {if (mat.length == 0) return 0;int M = mat.length;int N = mat[0].length;int[][] heights = new int[M][N]; // 上方有多少個連續的1for (int i = 0; i < N; i++) {heights[0][i] = mat[0][i] - 0;for (int j = 1; j < M; j++) {if (mat[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 += countRectangle(heights[i]);}return result;}// Reference:// leetcode 84. Largest Rectangle in Histogram// leetcode 85. Maximal Rectanglepublic int countRectangle(int[] heights) {int L = heights.length;// 找左邊第一個小于h[i]的數// 從右向左遍歷,維護單調不減棧,小數h[i]不斷將大數h[j]彈出,則h[i]左邊第一個小于h[i]的數為h[j]Stack<Integer> valueStack = new Stack<>();Stack<Integer> indexStack = new Stack<>();int[] leftIndex = new int[L]; // i左邊第一個小于i的數的下標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]的數// 從左向右遍歷,維護單調不減棧valueStack = new Stack<>();indexStack = new Stack<>();int[] rightIndex = new int[L]; // i右邊第一個小于i的數的下標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 totalRectangle = 0;boolean[][] seen = new boolean[L + 2][L + 2]; // from,tofor (int i = 0; i < L; i++) {if (seen[leftIndex[i] + 1][rightIndex[i] + 1]) continue; // 相同高度只需計算一次else seen[leftIndex[i] + 1][rightIndex[i] + 1] = true;int leftHeight = leftIndex[i] >= 0 ? heights[leftIndex[i]] : 0; // 左邊第一個小于h[i]的高度int rightHeight = rightIndex[i] < L ? heights[rightIndex[i]] : 0; // 右邊第一個小于h[i]的高度int validHeight = heights[i] - Math.max(leftHeight, rightHeight); // 自由的高度int validWidth = rightIndex[i] - leftIndex[i] - 1; // 自由的寬度if (heights[i] > 0) totalRectangle += (validWidth * (validWidth + 1) / 2) * validHeight;}return totalRectangle;} }總結
以上是生活随笔為你收集整理的leetcode 1504. Count Submatrices With All Ones | 1504. 统计全 1 子矩形(单调栈)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 212. Word S
- 下一篇: leetcode 622. Design