下一个更大元素II
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。
/**
* @param {number[]} nums
* @return {number[]}
*/
const nextGreaterElements = (nums = [1,2,1]) => {
const stack = []
const len = nums.length
const res = []
for(let i = len * 2 - 1; i > -1; i--){
while(stack.length && stack[stack.length - 1] <= nums[i % len]){
stack.pop()
}
res[i % len] = stack.length ? stack[stack.length - 1] : -1
stack.push(nums[i % len])
}
return res
};
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号