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;
    }
};
相关推荐
佑白雪乐14 分钟前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑17 分钟前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
平凡灵感码头22 分钟前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
哔哔龙27 分钟前
Android OpenCV 实战:图片轮廓提取与重叠轮廓合并处理
android·算法
hz_zhangrl30 分钟前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
x_xbx34 分钟前
LeetCode:1. 两数之和
数据结构·算法·leetcode
x_xbx36 分钟前
LeetCode:49. 字母异位词分组
算法·leetcode·职场和发展
玲娜贝儿--努力学习买大鸡腿版1 小时前
hot 100 刷题记录(1)
数据结构·python·算法
123过去1 小时前
pixiewps使用教程
linux·网络·测试工具·算法·哈希算法
深圳市快瞳科技有限公司1 小时前
低空经济下,鸟类识别算法与无人机硬件的兼容性优化策略
算法·无人机