496. 下一个更大元素 I 力扣(简单) 单调栈

496. 下一个更大元素 I

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

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

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

示例 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。
对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。
对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。

题解:https://leetcode-cn.com/problems/next-greater-element-i/solution/acmjin-pai-ti-jie-dan-diao-zhan-bian-che-knma/

单调栈

「找到最近一个比其大的元素」的字眼时,自然会想到「单调栈」

代码:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
    stack<int> s;
    map<int,int> mp;
    for(auto i:nums2)
    {
        if(s.empty() || s.top()>=i) s.push(i);
          else 
          {
              while(!s.empty() && s.top()<i)  // 如果左边小,可以弹出了,找到了右边最近最小的数字
              {
                  mp[s.top()]=i;
                  s.pop();
              }
              s.push(i);
          }
    }
    while(!s.empty()) {mp[s.top()]=-1; s.pop();}
    vector<int> res;
    for(auto i :nums1)
      res.push_back(mp[i]);
    return res;
    }
};
原文地址:https://www.cnblogs.com/stepping/p/15465571.html