代码随想录算法训练营day62

503.下一个更大元素II

思路: 循环数组中得到元素下一个比它大的值,那么可以将两个本数组拼接,遍历即可。按照739. 每日温度的方法,在拼接数组中进行寻找。

复制代码
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        vector<int> result(nums.size(),-1);
        if(nums.size()==0){
            return result;
        }
        stack<int> st;
        st.push(0);
        for(int i=1;i<nums.size()*2;i++){
            if(nums[i%nums.size()]<=nums[st.top()]){
                st.push(i%nums.size());
            }
            else{
                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. 接雨水

思路: 本体相当于求一个左右大于当前元素的位置,然后计算面积。要求左右比当前元素大,可以使用单调栈,使用递增栈,若当前元素大于栈顶,那么heighti与栈顶的下一个元素就为他的左右元素,取最小h,计算宽度,即可得到现在的与水量。然后遍历所有元素。

复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> st;
        st.push(0);
        int result = 0;
        for (int i = 1; i < height.size(); i++) {
            if (height[i] < height[st.top()]) {
                st.push(i);
            } else if (height[i] == height[st.top()]) {
                st.pop();
                st.push(i);
            } else {
                while (!st.empty() && height[i] > height[st.top()]) {
                    int mid = height[st.top()];
                    st.pop();
                    if (!st.empty()) {
                        int h = min(height[i], height[st.top()]) - mid;
                        int w = i - st.top() - 1;
                        result += h * w;
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};
相关推荐
wenyq727 分钟前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.1 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆1 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
不会代码的小猴2 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军3 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术3 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia4 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang4 小时前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow4 小时前
06 训练管线:数据如何变成权重
人工智能·算法