JavaScript Solution2 O(M+N)


  • 0
    var nextGreaterElement = function(findNums, nums) {
        let numStack = [nums[0]];
        let numsMap = new Map();
        for(let i=1; i<nums.length; ++i) {
          while (numStack.length > 0 && numStack[numStack.length - 1] < nums[i]) {
            numsMap.set(numStack[numStack.length - 1],nums[i]);
            numStack.pop();
          }
          numStack.push(nums[i]);
        }
        while(numStack.length > 0) {
          numsMap.set(numStack[numStack.length - 1], -1);
          numStack.pop();
        }
        return findNums.map(item => numsMap.get(item));
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.