下一个更大元素I

nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。

给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。

对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。

返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
const nextGreaterElement = (nums1 = [4,1,2], nums2 = [1,7,6,3,5,4,2]) => {
    const res = []
    const stack = []
    const map = new Map()
    for(let i = nums2.length - 1; i > -1; i--){
        while(stack.length && stack[stack.length - 1] <= nums2[i]){
            stack.pop()
        }
        map.set(nums2[i], stack.length ? stack[stack.length - 1] : -1)
        stack.push(nums2[i])
    }
    for(let i = 0; i < nums1.length; i++){
        res.push(map.get(nums1[i]))
    }
    return res
};

  感谢:https://www.cnblogs.com/echolun/p/14590131.html

posted @ 2023-02-04 23:30  671_MrSix  阅读(11)  评论(0编辑  收藏  举报