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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【LeetCode笔记】85. 最大矩形(Java、单调栈)

發布時間:2024/7/23 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode笔记】85. 最大矩形(Java、单调栈) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 題目描述
  • 思路 && 代碼
      • 二刷

題目描述

  • 其實是84. 柱狀圖中最大的矩形的兄弟題目,理解成多個84題,對結果取max即可。

思路 && 代碼

  • 一行抽象出一個【柱狀圖】,分別套到84題的函數里即可
  • 時空復雜度:O(n2n^2n2)、O(n)
class Solution {public int maximalRectangle(char[][] matrix) {if(matrix == null || matrix.length == 0) {return 0;}// 看成【對每層,進行柱狀圖最大面積判斷】即可(相當于固定底)int max = 0;int[] heights = new int[matrix[0].length];for(int i = 0; i < matrix.length; i++) {for(int j = 0; j < matrix[0].length; j++) {if(matrix[i][j] == '1') {heights[j]++;}else {heights[j] = 0;}}max = Math.max(max, largestRectangleArea(heights));}return max;}// 84. 求柱狀圖最大矩陣面積public int largestRectangleArea(int[] heights) {int res = 0;Deque<Integer> stack = new ArrayDeque<>();int[] newHeights = new int[heights.length + 2];for(int i = 1; i < heights.length + 1; i++) {newHeights[i] = heights[i - 1];}for(int i = 0; i < newHeights.length; i++) {while(!stack.isEmpty() && newHeights[stack.peek()] > newHeights[i]) {int index = stack.pop();int l = stack.peek();int r = i;res = Math.max(res, (r - l - 1) * newHeights[index]);}stack.push(i);}return res;} }

二刷

  • 思路還是記得的
class Solution {public int maximalRectangle(char[][] matrix) {if(matrix == null || matrix.length == 0) return 0;int[] heights = new int[matrix[0].length];int res = 0;// 逐行轉換for(int i = 0; i < matrix.length; i++) {// 當前行的逐列維護for(int j = 0; j < matrix[0].length; j++) {if(matrix[i][j] == '1') {heights[j]++;}else {heights[j] = 0;}}res = Math.max(res, largestRectangleArea(heights));}return res;}public int largestRectangleArea(int[] heights) {int[] newHeights = new int[heights.length + 2];for(int i = 1; i <= heights.length; i++) {newHeights[i] = heights[i - 1];}Deque<Integer> stack = new ArrayDeque<>();int max = 0;for(int i = 0; i < newHeights.length; i++) {while(!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {int now = stack.poll();int left = stack.peek(); int right = i; max = Math.max(max, (right - left - 1) * newHeights[now]);}stack.push(i);}return max;} }

總結

以上是生活随笔為你收集整理的【LeetCode笔记】85. 最大矩形(Java、单调栈)的全部內容,希望文章能夠幫你解決所遇到的問題。

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