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;
    }
};
相关推荐
血色橄榄枝4 小时前
基于用户注册信息的关键词检测挑战赛「Datawhale AI 夏令营」
人工智能·算法·机器学习
c238565 小时前
第二篇:《测试指挥官:可视化单题自测框架(含 assert 实操)》
java·数据库·c++·算法·安全性测试
六点_dn5 小时前
Linux学习笔记-printf命令
linux·运维·算法
遥感知识服务6 小时前
Sentinel-1 + DEM + FwDET + 随机森林:从快速水深初估到多因子误差修正
算法·随机森林·sentinel
来一碗刘肉面6 小时前
顺序表与链表的比较
数据结构·算法·链表
alphaTao7 小时前
LeetCode 每日一题 2026/7/13-2026/7/19
算法·leetcode
nnerddboy7 小时前
脑电信号处理实战 03 | 运动想象脑机接口入门:ERD/ERS、CSP 空间滤波与左右拳想象解码
算法·信号处理
QN1幻化引擎8 小时前
Dalin L — 我造了一门支持中文编程的语言,完整移植到 Rust 了
人工智能·算法·机器学习
Rainy Blue8838 小时前
C转C++速成
c语言·c++·算法
txzrxz8 小时前
二分图详解
数据结构·c++·算法·图论·深度优先搜索·二分图染色