408算法题leetcode--第26天

496. 下一个更大元素 I

题目地址496. 下一个更大元素 I - 力扣(LeetCode)

题解思路:单调栈,如注释

时间复杂度:O(n + m)

空间复杂度:O(n)

代码:

cpp 复制代码
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        // 单调栈:递增栈;存数字
        // 用哈希表存结果数组,用于num1输出
        stack<int>stk;
        unordered_map<int, int>mp;
        stk.push(nums2[0]);
        int size = nums2.size();
        for(int i = 0; i < size; i++){
            while(!stk.empty() && nums2[i] > stk.top()){
                mp[stk.top()] = nums2[i]; 
                stk.pop();
            }
            stk.push(nums2[i]);
        }
        // 输出
        vector<int>ret;
        size = nums1.size();
        for(int i = 0; i < size; i++){
            if(!mp.count(nums1[i])){
                ret.emplace_back(-1);
            } else {
                ret.emplace_back(mp[nums1[i]]);
            }
        }
        return ret;
    }
};

503. 下一个更大元素 II

题目地址503. 下一个更大元素 II - 力扣(LeetCode)

题解思路:注释

时间复杂度:O(n)

空间复杂度:O(n)

代码:

cpp 复制代码
class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        // 单调栈:先复制前面n-1个数到原数组的后面(用下标模拟即可),再用单调栈
        // 记录下标,递增栈
        int size = nums.size();
        vector<int>ret(size, -1);
        stack<int>stk;
        for(int i = 0; i < size * 2 - 1; i++){
            while(!stk.empty() && nums[stk.top()] < nums[i % size]){
                ret[stk.top()] = nums[i % size];
                stk.pop();
            }
            stk.push(i % size);
        }
        return ret;
    }
};
相关推荐
金銀銅鐵21 分钟前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC3 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
To_OC20 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent