代码随想录算法训练营第五十九天

想想其实坚持下来也不是很难,不过有很多题做一遍应该是记忆没那么深,anyway,要继续往换工作的方向走啊。加油!!

503.下一个更大元素II

想对了地方,但是没有坚持,应该搞两遍,就把所有的i都遍历过整个数组了。学到了。。。

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int>result(nums.size(),-1);
        stack<int>st;//用来记序号
        st.push(0);
        for(int i = 1;i< nums.size() * 2;i++){
            while(!st.empty() && nums[i % nums.size()] > nums[st.top()]){
                result[st.top()] = nums[i % nums.size()];
                st.pop();
            }
            st.push(i % nums.size());
        }
        return result;
    }
};

42. 接雨水 

今日做题没有斗志,随想录扶的。这题用双指针基本理解操作在干啥。

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.size() <= 2)return 0;
        int sum = 0;
        vector<int>heightl_max(height.size(),0);
        vector<int>heightr_max(height.size(),0);
        int size = height.size();
        heightl_max[0] = height[0];
        heightr_max[size - 1] = height[size - 1]; 
        for(int i = 1;i < size; i++){
            heightl_max[i] = max(height[i],heightl_max[i-1]);
        }
        for(int i = size -2;i >= 0;i--){
            heightr_max[i] = max(height[i],heightr_max[i+1]);
        }
        for(int i = 0;i < size;i++){
            if(i == 0 && i == size-1)continue;
            int count = min(heightl_max[i],heightr_max[i]) - height[i];
            if(count > 0)sum += count;
        }
        return sum;
    }
};

单调栈法

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.size() <= 2)return 0;
        stack<int>st;
        st.push(0);
        int sum = 0;
        for(int i = 1;i < height.size();i++){
            if(height[st.top()] > height[i]){
                st.push(i);
            }
            else if(height[st.top()] == height[i]){
                st.pop();
                st.push(i);
            }
            else{
                while(!st.empty() && height[st.top()] < height[i]){
                    int mid = st.top();
                    st.pop();
                    if(!st.empty()){
                        int h = min(height[i],height[st.top()]) - height[mid];
                        int w = i - st.top() - 1; //算的是一层,这个w很重要
                        sum += h * w;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
};

今天第二题也扶完了,有个印象。。。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值