您的位置:首页 > 职场人生

106_leetcode_largest Rectangle in Histogram

2014-06-23 18:05 190 查看
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

1:使用栈,依次遍历数组,索引如栈;2:索引出栈的时候,计算最大值,并且注意栈为null的情况

int largestRectangleArea(vector<int> &height)
{
if(height.size() == 0)
{
return 0;
}

int size = (int)height.size();
stack<int> myStack;
int maxValue = 0;

for(int i = 0; i < size; i++)
{
if(myStack.empty() || height[i] >= height[myStack.top()])
{
myStack.push(i);
}
else
{
while(!myStack.empty() && height[i] < height[myStack.top()])
{
int temp = height[myStack.top()];
int index = myStack.top();
myStack.pop();

int tempValue = temp * (!myStack.empty() ? i - index : i);
if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
myStack.push(i);
}
}

while(!myStack.empty())
{
int index = myStack.top();
int temp = height[index];
myStack.pop();

int tempValue = temp * (!myStack.empty() ? size - index : size);

if(tempValue > maxValue)
{
maxValue = tempValue;
}
}
return maxValue;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息