题目:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
分析
有个精彩详细的分析
http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
代码
先附上我自己写的没有用栈的方法
时间复杂度是O(2*n^2)
1 public static int largestRectangleArea3(int[] height) { 2 int maxArea = 0, left = 0, right = 0; 3 int[] h = Arrays.copyOf(height, height.length + 1); 4 5 for (int i = 0; i < height.length; i++) { 6 int j = 1; 7 while (i + j < h.length) { 8 if (h[i] <= h[i + j]) { 9 j++; 10 } else 11 break; // 没有break,会造成死循环。 12 } 13 right = i + j; 14 j = 0; 15 while (i - j - 1 >= 0) { 16 if (h[i] <= h[i - j - 1]) { 17 j++; 18 } else 19 break; 20 } 21 left = i - j; 22 maxArea = Math.max(maxArea, h[i] * (right - left)); 23 } 24 return maxArea; 25 }
然后是时间复杂度为O(n)的方法:
1 package StacksAndqueues; 2 3 import java.util.Arrays; 4 import java.util.Stack; 5 6 public class LargestRectangleInHistogram { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 int[] height= {2,1,5,6,2,3}; 11 System.out.println(largestRectangleArea(height)); 12 } 13 14 // LeetCode, Largest Rectangle in Histogram 15 // 时间复杂度 O(n),空间复杂度 O(n) 16 17 public static int largestRectangleArea(int[] height) { 18 Stack<Integer> stack = new Stack<Integer>(); 19 int[] h = new int[height.length + 1]; 20 h = Arrays.copyOf(height, height.length + 1); 21 int result = 0; 22 int i=0; 23 while(i < h.length) { //不能用for循环,要弹栈 24 if (stack.isEmpty() || h[i] >= h[stack.peek()])//stack里面只存放单调递增的索引 25 stack.push(i++); 26 else { 27 int t = stack.pop(); 28 result = Math.max(result, h[t] * (stack.isEmpty() ? i : i -1- stack.peek())); 29 }//栈内元素一定是要比当前i指向的元素小的。 30 } 31 return result; 32 } 33 }