503.下一个更大元素II
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:单调栈,成环了可怎么办?LeetCode:503.下一个更大元素II_哔哩哔哩_bilibili
状态:通过
代码实现:
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> st;
st.push(0);
vector<int> result(nums.size(), -1);
for(int i = 1; i < nums.size(); i++){
if(nums[i] <= nums[st.top()]){
st.push(i);
}
else{
while(!st.empty() && nums[i] > nums[st.top()]){
result[st.top()] = nums[i];
st.pop();
}
st.push(i);
}
}
for(int i = 0; i < nums.size(); i++){
if(nums[i] > nums[st.top()]){
while(!st.empty() && nums[i] > nums[st.top()]){
result[st.top()] = nums[i];
st.pop();
}
}
}
return result;
}
};
42. 接雨水
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:单调栈,经典来袭!LeetCode:42.接雨水_哔哩哔哩_bilibili
状态:未通过
代码实现:
class Solution {
public:
int trap(vector<int>& height) {
if(height.size() <= 2) return 0;
stack<int> st;
st.push(0);
int result = 0;
for(int i = 1; i < height.size(); i++){
if(height[i] > height[st.top()]){
while(!st.empty() && height[i] > height[st.top()]){
int mid = height[st.top()];
st.pop();
if(!st.empty()){
int high = min(height[st.top()], height[i]) - mid;
int width = i - st.top() - 1;
result += width * high;
}
}
}
st.push(i);
}
return result;
}
};