496. Next Greater Element I(单调栈)

https://leetcode.com/problems/next-greater-element-i/description/

题目:求出数组一中每个元素在第二个数组中对应位置的元素比它大的第一个数。

思路:单调栈(维护一个单调递增的栈,每次找到一个比栈顶元素大的元素,就将栈顶元素出栈,记录比栈顶元素大的元素的值,最后栈中元素比它大的元素都为-1)。

代码

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int len1=findNums.size(),len2=nums.size();

        map<int,int>m;
        vector<int>v;
        stack<int>s;

        for(int x=0;x<len2;x++){
            while(!s.empty()&&s.top()<nums[x]){
                  m[s.top()] = nums[x];
                  s.pop();
              }

            s.push(nums[x]);

            }

          while(!s.empty()) {
                  m[s.top()] = -1;
                  s.pop();
           }
          for(int num : findNums){
              v.push_back(m[num]);
          }

        return v;
    }
};

简化版:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int len1=findNums.size(),len2=nums.size();

        map<int,int>m;
        vector<int>v;
        stack<int>s;

        for(int x=0;x<len2;x++){
            while(!s.empty()&&s.top()<nums[x]){
                  m[s.top()] = nums[x];
                  s.pop();
              }

            s.push(nums[x]);

            }

          for(int num : findNums){
              v.push_back(m.count(num)==0?-1:m[num]);
          }

        return v;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

计算机的小粽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值