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;
}
}
很赞的参考:点击打开链接
仔细我们犯得错误!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;
}
}
相关文章推荐
- windows 环境下的 protoc 安装
- SQLite数据存储批量添加
- slidingmenu的应用
- OkHttp Post请求方式
- 29号流水账
- 微服务来了,监控怎么办?
- Httputils请求数据Pull解析
- osgi + felix example3编写与使用服务的改进
- Subarray Sum & Maximum Size Subarray Sum Equals K
- 《Eclipse.Rich.Client.Platform》chapter 6 Adding Actions
- 解决Exception: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z 等一系列问题
- [leetcode]123. Best Time to Buy and Sell Stock III
- json数据汉字打印
- 4.7 Python包的导入
- 《30天自制操作系统》学习笔记(五)
- 4.6 Python包
- 打印机驱动无法使用及打印机驱动彻底删除方法
- 4.5 Python dir()函数
- 第二章 省却记忆IP地址的烦恼-DNSv1
- centos7安装eclipse