class Solution {
public:
stack<int>st;
int res=0;
int trap(vector<int>& h)
{
for(int i=0;i<h.size();i++)
{
while(!st.empty()&&h[st.top()]<h[i])
{
int b = st.top();
//保留住栈顶元素 这是装雨容器的底h[b]
while(!st.empty()&&h[st.top()]==h[b])
{
st.pop();
}
//不断去除重复元素 找到栈里第一个比底部更大的元素 h[st.top()] 左边界
// h[i]右边界
if (!st.empty())
{
res += (min(h[st.top()], h[i]) - h[b]) * (i - st.top() - 1);
}
}
st.push(i);
}
return res;
}
};
class Solution {
public:
int trap(vector<int>& height)
{
int left = 0, right = height.size() - 1;
int l_max = 0, r_max = 0;
int res = 0;
while (left < right)
{
l_max = max(l_max, height[left]);
r_max = max(r_max, height[right]);
if (l_max < r_max)
{
res += l_max - height[left];
left++;
}
else {
res += r_max - height[right];
right--;
}
}
return res;
}
};
84柱状图中的最大矩形
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
stack<int>st;
int result = 0;
heights.insert(heights.begin(), 0);
heights.push_back(0);
st.push(0);
for(int i=1;i<heights.size();i++)
{
while(!st.empty()&&heights[i]<heights[st.top()])
{
int m=st.top();
st.pop();
int h=heights[m];
result=max(result,(i-st.top()-1)*h);
}
st.push(i);
}
return result;
}
};
11盛水最多的容器
class Solution {
public:
int maxArea(vector<int>& height)
{
int left = 0, right = height.size() - 1;
int res = 0;
while (left < right)
{
int cur_area = min(height[left], height[right]) * (right - left);
res = max(res, cur_area);
if (height[left] < height[right])
{
left++;
}
else
{
right--;
}
}
return res;
}
};
239滑动窗口最大值
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k)
{
int n=nums.size();
vector<int>res;
deque<int>q;
for(int i=0;i<n;i++)
{
if(!q.empty()&&i-k+1>q.front()) q.pop_front();
while(!q.empty()&&nums[q.back()]<nums[i])
{
q.pop_back();
}
q.push_back(i);
if (i>= k-1) res.push_back(nums[que.front()]);
}
return res;
}
};