leetcode——largestRectangleArea
来源:互联网 发布:云计算的未来发展趋势 编辑:程序博客网 时间:2024/06/02 03:15
题目描述
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 =10unit.
For example,
Given height =[2,1,5,6,2,3],
return10.
暴力:O(n^2)
#include <iostream>#include <vector>#include <string>#include <limits>#include <stack>using namespace std;class Solution {public:int largestRectangleArea(vector<int> &height) {int maxH = 0;int maxA = 0;for( int i= 0; i< height.size();i++){if( height[i] > maxH)maxH = height[i];}for( int h = 1; h<= maxH;h++){int maxLocal = 0;int maxT = 0;for( int i= 0; i< height.size();i++){if( height[i] >= h){maxT +=h;}else{if( maxLocal < maxT)maxLocal = maxT;maxT = 0;}}if( maxA < maxLocal){maxA = maxLocal;}}return maxA;}};int main(){string x = "()";vector<int > nn;nn.push_back(2);nn.push_back(1);nn.push_back(5);nn.push_back(6);nn.push_back(2);nn.push_back(3);//token.push_back("3");//token.push_back("*");Solution ss;cout<<ss.largestRectangleArea(nn);}
切头法:最坏O(n^2);最好O(n);平均O(n^2);
基本思路:
每次添加一个队尾:1、如果此时队列中身高都低于队尾,则直接添加;
2、如果队列中有人比队尾高,那么高出来的这部分在队尾之后就没有计算价值了,因为队尾的身高限制了连通高度,此时可以收割;
3、收割:指将队伍中比队尾高的队员切头,使其身高等于队尾,在切头的过程中,计算其贡献值,更新max。像割麦子一样。
此法很容易改写为O(n),只需要将vector 换位 stack
class Solution {public: int largestRectangleArea(vector<int> &height) { //使用栈,但我偏不。。int max = 0;vector<int> cnt;//最终队尾为0,最终全部切为0;height.push_back(0);for( int i = 0; i< height.size() ; i++){int k = i-1;int local = 0;while( k >= 0 && cnt[k] >= height[i]){//计算将被切头部分的最大值if( (i - k) * cnt[ k ] > local)local = (i - k) * cnt[ k ];//切头cnt[k] = height[i];k--;}if(max < local )max = local;//添加队尾cnt.push_back(height[i]);} return max; }};
0 0
- leetcode——largestRectangleArea
- 《leetCode》:largestRectangleArea
- LargestRectangleArea
- 开始刷刷Leetcode—leetcode第二题
- LeetCode —— Combinations
- LeetCode —— Triangle
- LeetCode —— Anagrams
- [leetcode] Subsets——@
- Permutations——LeetCode
- minimum_window_substring ——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Combinations
- LeetCode——Permutations
- *candy——leetcode
- gas_station——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- springmvc jsp无法访问静态同目录的css js文件
- 堆排序
- [C语言][LeetCode][86]Partition List
- 自定义控件开关,绘制图片。
- Pku1200 Crazy Search(Rabin Karp)
- leetcode——largestRectangleArea
- 字符串的翻转问题
- REST 在Servlet容器中运行
- POJ 2817 WordStack
- arcgis_标注功能
- 程序员你为什么迷茫?
- 第二章ROS机器人操作系统的总体框架
- 利用 Travis CI 把 Android 项目部署到 github
- 在myeclipse10 下搭建ssh环境