# 496.Next Greater Element I

**496.Next Greater Element I**

难度:Easy

> 给定两个没有重复元素的数组 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。
示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
    对于num1中的数字2，第二个数组中的下一个较大数字是3。
    对于num1中的数字4，第二个数组中没有下一个更大的数字，因此输出 -1。
注意:

nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。
```

可以熟悉下find函数的用法，

```
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        if(!nums1.size()) return res;
        for(auto x:nums1)
        {
            auto ind=find(nums2.begin(),nums2.end(),x);
            while(ind <nums2.end())
            {
                if(*ind > x)
                {
                    res.push_back(*ind);
                    break;
                }
                ind++;
            }
            if(ind ==nums2.end())
                res.push_back(-1);
        }
        return res;
    }
};
```

另一种方法，利用HashMap存储nums2中所有数的下一个最大值，然后直接查找即可。

```
class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res(nums1.size(),-1);
        if(!nums1.size()) return res;
        stack<int>pt;
        unordered_map<int,int>nextg;
        pt.push(nums2[0]);
        for(int i=1;i<nums2.size();i++)
        {
            while(!pt.empty() && pt.top()<nums2[i])
            {
                nextg[pt.top()]=nums2[i];
                pt.pop();
                
            }
            
            pt.push(nums2[i]);
        }
        for(int i=0;i<nums1.size();i++)
            if(nextg.count(nums1[i])) res[i]=nextg[nums1[i]];
        return res;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/496.next_greater_element_i.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
