LintCode 1201. The next bigger number II JavaScript algorithm

description

Given a circular array (the next element of the last element is the first element of the array), print the next larger element for each element. The next higher number of the number x is the first higher number that appears in the next traversal sequence in the array, which means you can loop through the search to find the next higher number. If it does not exist, -1 is output for this number.

Description

The length of the given array does not exceed 10000.

Sample

-1:

输入: [1,2,1]
输出: [2,-1,2]
解释:第一个1的下一个更大的数字是2;
数字2找不到下一个更大的数字;
第二个1的下一个更大的数字需要循环搜索,答案也是2

-2:

输入: [1]
输出: [-1]
解释:
数字1找不到下一个更大的数字

Parsing

const nextGreaterElements = function (nums) {
    
    
    var res = [];
    var _nums = nums.concat(nums);
    for(var i=0;i<nums.length;i++){
    
    
        var flag = true;
        for(var j=i+1;j<_nums.length;j++){
    
    
            if(nums[i]<_nums[j]){
    
    
                res.push(_nums[j]);
                flag = false;
                break;
            }
        }
        if(flag) res.push(-1);
    }
    return res;
}

operation result

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/108635721