题目
解题
与 LeetCode739 每日温度 一样,都是使用单调栈来求解,不同的是 739 题存储的是数组下标,这题存储的是数组值。
//
var nextGreaterElement = function(nums1, nums2) {
let nums1Len = nums1.length;
let res = new Array(nums1Len);
let stack = new Array();
let resMap = new Map();
for (let num of nums2) {
while (!isEmpty(stack) && num > peek(stack)) {
let last = stack.pop();
resMap.set(last, num);
}
stack.push(num);
}
for (let i = 0; i < nums1Len; i++) {
res[i] = resMap.has(nums1[i]) ? resMap.get(nums1[i]) : -1;
}
return res;
};
var isEmpty = function(stack) {
return stack.length === 0;
};
var peek = function(stack) {
if (isEmpty(stack)) return Infinity;
else return stack[stack.length - 1];
};