Leetcode中用Js实现Next Greater Element II

题目描述

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

翻译:

给定一个圆形数组(最后一个元素的下一个元素是数组的第一个元素),为每个元素打印下一个更大的数字。数字x的下一个较大的数是数组中按遍历顺序Next的第一个较大的数,这意味着您可以循环搜索找到它的下一个较大的数。如果不存在,则输出-1。

 

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function(nums) {
    var items = []
    var nums1=[];
    var flag = 0;
//将nums中的内容重复两遍放入nums1中
    for(var i=0;i<nums.length;i++){
        nums1[i] = nums[i]
        nums1[i+nums.length] = nums[i]
    }
    for(var i = 0;i<nums.length;i++){
        for(var j=i+1;j<nums1.length;j++){
            if(nums[i]<nums1[j]){
                items.push(nums1[j]);
                flag = 1;
                break;
            }
        }
        if(flag ===1){
            flag = 0;
        }else{
            items.push(-1)
        }
    
    }
    return items
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值