> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/stack/wei-chi-di-zeng-huo-di-jian/next-greater-element-i.md).

# Next Greater Element I

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

> You are given two array&#x73;**(without duplicates)**`nums1`and`nums2`where`nums1`’s elements are subset of`nums2`. Find all the next greater numbers for`nums1`'s elements in the corresponding places of`nums2`.
>
> The Next Greater Number of a number**x**in`nums1`is the first greater number to its right in`nums2`. If it does not exist, output -1 for this number.

## Thoughts

刚开始理解错了题意，以为是找比nums1各元素大的数。后来发现是找在nums2中排在该元素右边的遇到的第一个最大的数。还有个比较容易弄错的是nums1如何排列实际上没有任何关系。

stack的另一个应用，只存递减的元素，把不符合的抛出。新push进去的即那些被抛出的右边遇到的第一个比它们大的元素。

## Code

```
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums2.length; i++) {
            if (stack.isEmpty()) {
                stack.push(nums2[i]);
            } else {
                while (!stack.isEmpty() && nums2[i] > stack.peek()) {
                    map.put(stack.pop(), nums2[i]);
                }
                stack.push(nums2[i]);
            }
        }
        int[] res = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            if (map.containsKey(nums1[i])) {
                res[i] = map.get(nums1[i]);
            } else {
                res[i] = -1;
            } 
        }
        return res;
    }
}
```

## Analysis

时空复杂度都是O(n).
