这道题用的是堆栈,一开始想到解法了,但是写的实在是太混乱导致代码,于是搜了个非常简洁的方法,仅作记录。同时把i长数组变成i+1长的方法是new array=Arrays.copyof(old array, length),新的也可以比旧的短用于截取。
public int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int i = 0;
int maxArea = 0;
int[] h = new int[height.length + 1];
h = Arrays.copyOf(height, height.length + 1);
while(i < h.length){
if(stack.isEmpty() || h[stack.peek()] <= h[i]){
stack.push(i++);
}else {
int t = stack.pop();
maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return maxArea;
}