【字节跳动】2018散招实习面试题
题目地址:
求数组直方图最大面积:https://leetcode.com/problems/largest-rectangle-in-histogram/
解题思路:
AC代码:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);
int len = heights.size();
stack<int> increaseStack; //单调递增栈中存放的是位置
int ret = 0;
for (int i = 0; i < len; i++) {
while (!increaseStack.empty() && heights[increaseStack.top()] > heights[i]) {
// 找出当前的位置
int pos = increaseStack.top();
increaseStack.pop();
// 左边界为l, 有边界为i
int l = increaseStack.empty() ? -1 : increaseStack.top();
ret = max(ret, heights[pos] * (i - 1 - l));
}
increaseStack.push(i);
}
return ret;
}
};
关于此题的进阶版本:https://leetcode.com/problems/maximal-rectangle/
可以对每一层构造高度矩阵,然后求最大面积即可。
更多子数组相关的题目可参考:lintcode 子数组问题(最全的面试子数组问题)
其中列表最后面的POJ 2796和此题目极为相似。