您的位置:首页 > 其它

[LeetCode] Largest Rectangle in Histogram

2014-06-08 09:47 357 查看
第一种方法,暴力求解,从当前向左右两个方向扫描比自己小的,然后计算面积,时间复杂度O(n^2)code如下,但是在LeetCode上回超时。

class Solution {
public:
int largestRectangleArea(vector<int> &height) {

int size = height.size();
int left = 0, right = 0, area = 0;

for(int i = 0; i < size; i++)
{
int j;
for( j = i-1; j>= 0;j--)
{
if(height[j] <height[i])
{
left = j;
break;
}
}

for(j = i+1; j<size; j++)
{
if(height[j] <height[i])
{
right = j;
break;
}
}

area = max(area, height[i] * (right - left -1));
}

return area;

}
};


第二种方法,对于每一个height[i],第一种方法用暴力查找的方法找它的左右边界,我们可以用一个stack来实现其左右边界的查找。我们维持一个递增的栈,由于是递增的,后压入栈的都比前面的大,所以其左边界就确定了,我们要做的是找右边界。当某一个height[j]小于当前栈顶元素时,就找到了右边界,则将计算以当前栈顶元素计算为高得面积;如果下一个栈顶元素还是大于height[j],则仍要计算面积,以此类推,知道最后,我们一下图举例。

对原有的height在末尾压入0.

初始,stack为空,

i = 0, push idx=0 into stack;

i = 1, height[1] = 7 > height[stack.top()] = 2, push idx=1 into stack;

i = 2, height[2] = 5 < height[stack.top()] = 7,pop idx=2 from stack, calc area = (i-stack.top()-1)*height[idx] = (2-0-1)*7=7;

   height[2] = 5 > height[stack.top()] = 2, stop to calc area and push 5 into stack.

i = 3, height[3] = 6 > height[stack.top()] = 5, push idx = 3 into stack;

i = 4, height[4] = 4 < height[stack.top()] = 6, pop idx = 3 from stack, calc area = (i-stack.top()-1)*height[idx]= (4-2-1)*6=6,

   height[4] = 4 < height[stack.top()] = 5, pop idx =2 from stack, calc area =(i-stack.top()-1)*height[idx]=(4-0-1)*5=15,

   height[4] = 4 > height[stack.top()] = 2, push idx= 4 into stack;

i = 5 height[5] = 0 < height[stack.top()] = 2, pop idx =0 form stack, calc area = i*height[idx]= 5 * 2 = 10;

所以最大面积为15.



class Solution {
public:
int largestRectangleArea(vector<int> &height) {

//add 0 to the end
height.push_back(0);

int size = height.size(); //this new_size is 1 + old_size
stack<int> st;

int max_area = 0;

for(int i = 0; i< size; )
{
if(st.empty() || height[i] > height[st.top()])
{
st.push(i);
i++;
}
else
{
//st must be not empty here
// i can't ++; handle many times perhaps

int idx = st.top();
st.pop();

int area;

if(st.empty())
{
area = height[idx] * i;
}
else
{
area = height[idx] * (i-st.top()-1);
}

max_area = max(max_area, area);

}
}
return max_area;
}
};
f
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: