您的位置:首页 > 其它

Largest Rectangle in Histogram

2016-07-01 08:05 183 查看
单调栈,课上的知识今天终于用上了,不过好像就用上这三个字了,哈哈哈哈。

很赞的参考:点击打开链接

仔细我们犯得错误!stack里保存的是位置index,高度得用heights[stack.peek()]来得到。

public class Solution {
public int largestRectangleArea(int[] heights) {
if (heights == null) {
throw new IllegalArgumentException("haha");
}
if (heights.length == 0) {
return 0;
}
int maxArea = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < heights.length; i++) {
if (stack.empty()) {
stack.push(i);
} else {
//while (!stack.empty() && heights[i] < stack.peek()) {
while (!stack.empty() && heights[i] < heights[stack.peek()]) {
//int last_height = stack.pop();
int last_height = heights[stack.pop()];
if (!stack.empty()) {
maxArea = Math.max(maxArea, (i - 1 - stack.peek())*last_height);
} else {
maxArea = Math.max(maxArea, i*last_height);
}
}
stack.push(i);
}
}
while (!stack.empty()) {
//int last_height = stack.pop();
int last_height = heights[stack.pop()];
if (!stack.empty()) {
maxArea = Math.max(maxArea, (heights.length - 1 - stack.peek())*last_height);
} else {
maxArea = Math.max(maxArea, heights.length*last_height);
}
}
return maxArea;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: