题目描述
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
};