首页 > 其他分享 >下一个更大元素II

下一个更大元素II

时间:2023-02-05 00:12:41浏览次数:39  
标签:const nums 元素 II length 更大 stack

给定一个循环数组 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
};

  

标签:const,nums,元素,II,length,更大,stack
From: https://www.cnblogs.com/zhenjianyu/p/17092678.html

相关文章