leetcode——largestRectangleArea

题目描述


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.

leetcode——largestRectangleArea_第1张图片

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;
    }
};



你可能感兴趣的:(LeetCode,C++)