pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

下一个更大元素 I #1013

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

496. 下一个更大元素 I

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var nextGreaterElement = function(nums1, nums2) {
    const hash = {},
        stack = [],
        len = nums2.length;
    for(let i=0; i<len; i++) {
        let last = stack.length - 1;
        if(last == -1 || stack[last] > nums2[i]) {
            stack.push(nums2[i]);
            continue;
        }
        hash[stack[last]] = nums2[i];
        stack.pop();
        i--;
    }
    stack.forEach(value => {hash[value] = -1});
    return nums1.map(value => hash[value]);
};