[leetcode] Largest Rectangle in Histogram——惊天动地的代码@

这是一篇关于解决LeetCode问题的文章,主要探讨如何找到非负整数数组(柱状图的高度)中最大矩形的面积。文章提到了一个时间复杂度为o(n^2)的解决方案,指出此算法不适用于大数据,并提及一种思路是针对每个点找到左右边界以计算最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 height = [2,1,5,6,2,3],
return 10.

这道题目有点类似于求连续的子数组和最大的题

o(n**2)的时间复杂度算法如下,这个是过不了大数据的:

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int min=INT_MAX;
		int maxmum=0;
		int n=height.size();
		for(int i=0 ; i<n ; i++){
			for(int j=i ; j<n ; j++){
				if(height[j]<min)
					min=height[j];
				if(min*(j-i+1)>maxmum)
					maxmum=min*(j-i+1);
			}
			min=INT_MAX;
		}
		return maxmum;
	}
};

有一个思路是对于某一个点找到能到达的最左边和最右边,记录下来,最后计算最大值。

class Solution {
public:
	int largestRectangleArea(vector<int> &height) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int count=height.size();
		int *left=new int[count];
		int *right=new int[count];
		int j;
		for(int i=0 ; i<count ;  i++){
			for(j=i ; j>=0 && height[j]>=height[i]; j--);
			left[i]=j;
			for(j=i ; j<count && height[j]>=height[i] ; j++);
			right[i]=j;
		}
		int max=0;
		for(int i=0 ; i<count ; i++){
			if(height[i]*(right[i]-left[i]-1)>max)
				max=height[i]*(right[i]-left[i]-1);
		}
		delete left,right;
		return max;
	}
};


下面这个代码实在是太疯狂了

int largestRectArea(vector<int> &h) {
	stack<int> p;
	int i = 0, m = 0;
	h.push_back(0);
	while(i < h.size()) {
		if(p.empty() || h[p.top()] <= h[i])
			p.push(i++);
		else {
			int t = p.top();
			p.pop();
			m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 ));
		}
	}
	return m;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值