日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 1504. Count Submatrices With All Ones | 1504. 统计全 1 子矩形(单调栈)

發布時間:2024/2/28 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 子矩形(单调栈)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。