leetcode503. 下一个更大元素 II 单调栈

思路:

与之前 739、1475 单调栈的问题如出一辙,唯一不同的地方就是对于遍历完之后。栈中元素的处理,之前的栈中元素因无法找到符合条件的值,直接加入vector中。而这里需要再重头遍历一下数组,找是否有符合条件的,如果仍然找不到的话,才会把它赋值然后加入vector中。

代码:

cpp 复制代码
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(n);
        stack<int> st;
        for (int i = 0; i < n; i++) {
            int t = nums[i];
            // 出栈并计算
            while (!st.empty() && t > nums[st.top()]) {
                int x = st.top();
                ans[x] = t;
                st.pop();
            }
            // 入栈
            while (st.empty() || (t <= nums[st.top()] && i != st.top())) {
                st.push(i);
            }
        }
        // 处理遍历完之后,栈中剩余的元素。
        while (!st.empty()) {
            int x = st.top();
            // 从头遍历数组看是否有符合要求的值。
            int i = 0;
            for (i = 0; i < n; i++) {
                if (nums[i] > nums[x]) {
                    ans[x] = nums[i];
                    break;
                }
            }
            if (i == n) ans[x] = -1;
            st.pop();
        }
        return ans;
    }
};

注意点:

for循环中的入栈出栈顺序非常重要!!!

出栈放在最后,则新元素无法入栈。

运行结果:

相关推荐
三毛的二哥4 小时前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
南宫萧幕4 小时前
自控PID+MATLAB仿真+混动P0/P1/P2/P3/P4构型
算法·机器学习·matlab·simulink·控制·pid
故事和你916 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
我叫黑大帅6 小时前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头6 小时前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者7 小时前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
破浪前行·吴7 小时前
数据结构概述
数据结构·学习
py有趣8 小时前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒9 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼9 小时前
LeetCodehot100-394 字符串解码
算法