您的位置:首页 > 编程语言

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

2013-08-16 19:11 417 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: