day 59 503.下一个更大元素II 42. 接雨水

文章介绍了如何使用单调栈解决C++中的两个问题:vector的扩充操作以及雨水收集问题。通过分析数组并维护单调性,作者提供了Solution类的实现,包括nextGreaterElements函数和trap函数,展示了在不同场景中运用栈数据结构优化算法的过程。

vector的扩充要熟悉

vector<int> numsT(nums.begin(),nums.end());

 nums.insert(nums.end(),numsT.begin(),numsT.end());

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        stack<int> st;
        
        vector<int> numsT(nums.begin(),nums.end());
        nums.insert(nums.end(),numsT.begin(),numsT.end());
        vector<int> res(nums.size(),-1);
        st.push(0);
        int index=1;
        while(!st.empty()&&index<nums.size()){
            while(index<nums.size()&&nums[index]<=nums[st.top()]){
                st.push(index);
                index++;
            }
            while(!st.empty()&&index<nums.size()&&nums[index]>nums[st.top()]){
                res[st.top()]=nums[index];
                st.pop();
            }
            st.push(index);
            index++;
            
        }
        return vector <int>(res.begin(),res.begin()+numsT.size());
        
    }
};

vector.resize()-》

result.resize(nums.size() / 2);

可以模拟走了两遍数组 

不知道咋转为单调栈

题解:代码随想录

按照列计算,这样只要计算高度。有多种解法,首先是双指针解法,对于每个位置,遍历最右边和最左边最高高度,找到两者最小值-本列高度,就能得到当前装的雨水高度。更进一步是,每列的左侧最高高度转为左边一列的左侧最高高度和左侧一列的高度最大值,右侧类似,减少重复计算。

maxLeft[i] = max(height[i], maxLeft[i - 1]);

单调栈解法:是按行做

要用单调增的单调栈,如果新加的元素比栈头大,栈头就是底部,栈头左边是最近的比他高的左边柱子。因为我们要求宽度的时候 如果遇到相同高度的柱子,需要使用最右边的柱子来计算宽度,所以相同值要替换下标。栈里保存下表,通过长*宽算雨水体积。

一次wa是因为stack弹出元素后要取栈顶元素之有特判stack是否为空

class Solution {
public:
    int trap(vector<int>& height) {
        stack <int> st;
        st.push(0);
        int index=1;
        if(height.size()<=2){
            return 0;
        }
        int sum=0;
        while(!st.empty()&&index<height.size()){
            while(!st.empty()&&index<height.size()&&height[index]<height[st.top()]){
                st.push(index);
                index++;
            }
            while(!st.empty()&&index<height.size()&&(height[index]==height[st.top()])){
                st.pop();
                st.push(index);
                index++;
            }
            while(!st.empty()&&index<height.size()&&height[index]>height[st.top()]){
                int mid=st.top();
                st.pop();
                if(! st.empty()){
                int h=min(height[index],height[st.top()])-height[mid];
                int w=index-st.top()-1;
                sum+=h*w;
                }

            }
            st.push(index);
            index++;
        }
        return sum;

    }
};

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值