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;
    }
};
相关推荐
梁下轻语的秋缘28 分钟前
C/C++滑动窗口算法深度解析与实战指南
c语言·c++·算法
iFulling32 分钟前
【数据结构】第八章:排序
数据结构·算法
一只鱼^_33 分钟前
力扣第448场周赛
数据结构·c++·算法·leetcode·数学建模·动态规划·迭代加深
寂空_1 小时前
【算法笔记】动态规划基础(二):背包dp
笔记·算法·动态规划
搏博2 小时前
神经网络在专家系统中的应用:从符号逻辑到连接主义的融合创新
人工智能·深度学习·神经网络·算法·机器学习
Eric.Lee20212 小时前
数据集-目标检测系列- 印度人脸 检测数据集 indian face >> DataBall
人工智能·算法·目标检测·计算机视觉·yolo检测·印度人脸检测
E___V___E2 小时前
线性DP(动态规划)
算法·动态规划
vibag2 小时前
启发式算法-禁忌搜索算法
java·算法·启发式算法·禁忌搜索
白露秋483 小时前
数据结构——算法复杂度
数据结构·算法·哈希算法
我是一只鱼02233 小时前
LeetCode算法题 (移除链表元素)Day15!!!C/C++
c++·算法·leetcode·链表