42. 接雨水
接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。
建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。
在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。
class Solution {
public:
int trap(vector<int>& height) {
stack<int>st;
int res=0;
for (int i=0;i<height.size();i++){
if (st.empty() || height[st.top()]>height[i])st.push(i);
else{
while(!st.empty() && height[st.top()]<height[i]){
int mid=st.top();
st.pop();
if (!st.empty())res+=(i-st.top()-1)*(min(height[st.top()],height[i])-height[mid]);
}
st.push(i);
}
}
return res;
}
};
总结
把左边最大和右边最大就是要求面积的思路理清楚了其实后面实现就不难了。
84. 柱状图中最大的矩形
有了之前单调栈的铺垫,这道题目就不难了。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int>st;
heights.insert(heights.begin(), 0); // 数组头部加入元素0
heights.push_back(0); // 数组尾部加入元素0
st.push(0);
int res=0;
for (int i=1;i<heights.size();i++){
if (st.empty() || heights[st.top()]<heights[i])st.push(i);
else{
while (!st.empty() && heights[st.top()]>heights[i]){
int mid=st.top();
st.pop();
if (!st.empty())res=max(res,heights[mid]*(i-st.top()-1));
else res=max(res,heights[mid]*i);
}
st.push(i);
}
}
return res;
}
};
总结
我还在想怎么把栈剩余的元素给算上,原来在后面加上个0就可以了。