---
# System prepended metadata

title: \#496 Next Greater Element I
tags: [array, leetcode, leetcode-easy]

---

# \#496 Next Greater Element I
## *給定兩正整數陣列nums1, nums2, 其中nums1是nums2的子陣列(即nums1的所有元素皆有在nums2內出現), 回傳每個nums1元素中, 出現在nums2的"下一個更大元素"的值(回傳陣列型態), 如果沒有則為-1*
## Log
 - build 20210925 by syhuang

## xxx
 - xxx
 - leetcode submit runtime xx%, memory xx%
```javascript=
```
## 初見
 - 對nums1跑迴圈找出在nums2中出現的位置
 - 從nums2的該位置開始往後找,紀錄找到的第一個較大數字; 沒找到就紀錄-1
 - 時間複雜度O(n^2)
 - leetcode submit runtime 31%, memory 53%
```javascript=
var nextGreaterElement = function(nums1, nums2) {
    let result = [];
    nums1.forEach(function(value,index){
        let ifFindNum = false;
        for(let i=nums2.findIndex(findNum); i<nums2.length; i++){
            if(nums2[i]>value){
                result.push(nums2[i]);
                ifFindNum = true;
                break;
            }
        }
        if(result.length != index+1) result.push(-1);
        function findNum(elm){
            return elm===value;
        }
    });
    return result;
};
```
## 備註
- [monotone stack解(時複O(n))](https://leetcode.com/problems/next-greater-element-i/discuss/97595/Java-10-lines-linear-time-complexity-O(n)-with-explanation)
## 參考
###### tags: `leetcode`, `leetcode-easy`, `array`