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;
}
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;
}
相关文章推荐
- 106_leetcode_Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram 解题报告
- LeetCode —— Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram(直方图最大面积)
- LeetCode-Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram
- leetcode-084:Largest Rectangle in Histogram
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram、Maximal Rectangle
- [leetcode]Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram
- [leetcode] Largest Rectangle in Histogram
- [leetcode]Largest Rectangle in Histogram
- leetcode之Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- leetcode - Largest Rectangle in Histogram
- leetcode -- Largest Rectangle in Histogram TODO O(N)
- LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram