vue 增加loading指令
阿新 • • 發佈:2020-10-29
柱狀圖中最大的矩形
難度困難783
給定 n 個非負整數,用來表示柱狀圖中各個柱子的高度。每個柱子彼此相鄰,且寬度為 1 。
求在該柱狀圖中,能夠勾勒出來的矩形的最大面積。
以上是柱狀圖的示例,其中每個柱子的寬度為 1,給定的高度為 [2,1,5,6,2,3]
。
圖中陰影部分為所能勾勒出的最大矩形面積,其面積為 10
個單位
示例:
輸入: [2,1,5,6,2,3]輸出: 10
方法一:暴力
固定高度,向兩邊找邊
public int largestRectangleArea(int[] heights) { int maxArea = 0; for (int i = 0; i < heights.length; i++) { int left = 0; int right = heights.length - 1; for(int j = i - 1; j >= 0; j--) { if (heights[j] < heights[i]) { left = j + 1; break; } } for(int j = i + 1; j < heights.length; j++) { if (heights[j] < heights[i]) { right = j - 1; break; } } maxArea = Math.max(maxArea, heights[i] * (right -left + 1)); } return maxArea; }
固定邊
public int largestRectangleArea(int[] heights) { int maxArea = 0; for (int i = 0; i < heights.length; i++) { int minHeight = heights[i]; for (int j = i; j <heights.length; j++) { minHeight = Math.min(minHeight, heights[j]); maxArea = Math.max(maxArea, minHeight * (j - i + 1)); } } return maxArea; }
方法二:單調棧
public int largestRectangleArea(int[] heights) { int maxArea = 0; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < heights.length; i++) { while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) { int height = heights[stack.pop()]; int width; if (stack.isEmpty()) { width = i; } else { width = i - stack.peek() - 1; } maxArea = Math.max(maxArea, height * width); } stack.push(i); } while (!stack.isEmpty()) { int height = heights[stack.pop()]; int width; if (stack.isEmpty()) { width = heights.length; } else { width = heights.length - stack.peek() - 1; } maxArea = Math.max(maxArea, height * width); } return maxArea; }
哨兵
public int largestRectangleArea(int[] heights) {
int len = heights.length;
int maxArea = 0;
Stack<Integer> stack = new Stack<>();
int[] newHeights = new int[len + 2];
System.arraycopy(heights, 0, newHeights, 1, len);
heights = newHeights;
len += 2;
stack.push(0);
for (int i = 1; i < len; i++) {
while (heights[i] < heights[stack.peek()]) {
int height = heights[stack.pop()];
int width = i - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}