接雨水这道题目是 面试中特别高频的一道题,也是单调栈 应用的题目,大家好好做做。
建议是掌握 双指针 和单调栈,因为在面试中 写出单调栈可能 有点难度,但双指针思路更直接一些。
在时间紧张的情况有,能写出双指针法也是不错的,然后可以和面试官在慢慢讨论如何优化。
代码随想录
class Solution { public: int trap(vector& height) { stackst; int res=0; for (int i=0;iheight[i])st.push(i); else{ while(!st.empty() && height[st.top()] 把左边最大和右边最大就是要求面积的思路理清楚了其实后面实现就不难了。
有了之前单调栈的铺垫,这道题目就不难了。
ongjiez代码随想录
class Solution { public: int largestRectangleArea(vector& heights) { stackst; heights.insert(heights.begin(), 0); // 数组头部加入元素0 heights.push_back(0); // 数组尾部加入元素0 st.push(0); int res=0; for (int i=1;iheights[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就可以了。