[leetcode]84. Largest Rectangle in Histogram c语言
来源:互联网 发布:手机域名价格 编辑:程序博客网 时间:2024/06/16 01:00
题目
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 heights = [2,1,5,6,2,3],
return 10.
思路
自己能想到就是O(n2)的解法(依次算每个高度能形成的最大面积),时间超过限制。学习了下其他人的解法http://blog.csdn.net/doc_sgl/article/details/11805519
从左依次遍历高度数组,高度有增加时,就把每个下标依次存在栈中,当有断崖出现时。就出栈并计算断崖前的最大面积。理解栈中始终存着一个阶梯状的高度下标。
int largestRectangleArea(int* heights, int heightsSize) { int *stack = NULL, max = 0; int *dupHeights = NULL; int top = -1; int area = 0; int i; if(!heights || !heightsSize) return 0; stack = (int *)malloc(heightsSize * sizeof(int)); if(!stack) return 0; dupHeights = (int *)malloc((heightsSize + 1) * sizeof(int)); if(!dupHeights) return 0; /* 末尾追加高度0,以便最后出栈所有下标 */ memcpy(dupHeights, heights, heightsSize * sizeof(int)); dupHeights[heightsSize] = 0; for(i = 0; i < heightsSize + 1; ) { if(top == -1 || dupHeights[i] >= dupHeights[stack[top]]) { top++; stack[top] = i; i++; } else { if(top == 0) { area = dupHeights[stack[top]] * i; top--; } else { area = dupHeights[stack[top]] * (i - stack[top-1] - 1); top--; } if(max < area) max = area; } } free(stack); free(dupHeights); return max;}
Run Time:8ms
0 0
- [leetcode]84. Largest Rectangle in Histogram c语言
- 【C++】LeetCode 84. Largest Rectangle in Histogram
- [leetcode-84]Largest Rectangle in Histogram(c++)
- [Leetcode] 84. Largest Rectangle in Histogram
- LeetCode --- 84. Largest Rectangle in Histogram
- [LeetCode]*84.Largest Rectangle in Histogram
- [leetcode] 84.Largest Rectangle in Histogram
- [leetcode] 84. Largest Rectangle in Histogram
- Leetcode 84. Largest Rectangle in Histogram
- **LeetCode 84. Largest Rectangle in Histogram
- leetcode 84. Largest Rectangle in Histogram
- leetcode 84. Largest Rectangle in Histogram
- 【leetcode】84. Largest Rectangle in Histogram
- LeetCode 84. Largest Rectangle in Histogram
- LeetCode-84.Largest Rectangle in Histogram
- leetcode.84. Largest Rectangle in Histogram
- [leetcode] 【栈】 84. Largest Rectangle in Histogram
- Leetcode 84. Largest Rectangle in Histogram
- 详解https是如何确保安全的
- CodeForces - 659A Round House (形成环)水
- 如何安装配置gradle及eclipse的结合
- ACM输入问题以及矩阵最大路径累加和
- 【Vuforia】Vuforia实现自动对焦
- [leetcode]84. Largest Rectangle in Histogram c语言
- STL学习笔记
- 自定义ScrollView+自定义滚动条
- Akka并发编程——第五节:Actor模型(四)
- 适配器模式----类适配和对象适配
- [查异常网]-20160402-解决「问题」,不要解决问题
- svn1
- JAVA实现LDAP连接验证
- 学习计划