Leetcode 496. 下一个更大元素 I 【简单】

题目如下:

给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。

请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

 

提示:

1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1和nums2中所有整数 互不相同
nums1 中的所有整数同样出现在 nums2 中
 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-i

 

解题思路:

对nums2使用单调栈,获得nums2中所有元素的下一个比他大的数值,没有则为 -1 ,使用哈希表存储元素以及其对应的下一个比他大的数。

 

代码:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        map<int,int> M;
        stack<int> S;
        S.push(nums2[0]);
        for(int i=1;i<nums2.size();i++){
            while(!S.empty()&&S.top()<nums2[i]){
                M[S.top()]=nums2[i];
                S.pop();
            }
            S.push(nums2[i]);
        }
        vector<int> ans(nums1.size(),-1);
        for(int i=0;i<ans.size();i++){
            if(M.find(nums1[i])!=M.end()){
                ans[i]=M[nums1[i]];
            }
        }
        return ans;
    }
};

 

总结:

熟悉使用单调栈。

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值