您的位置:首页 > 其它

leetcode做题总结,题目Largest Rectangle in Histogram 2012/04/22

2014-10-04 12:48 363 查看
这道题用的是堆栈,一开始想到解法了,但是写的实在是太混乱导致代码,于是搜了个非常简洁的方法,仅作记录。同时把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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: