修改 0503.下一个更大元素II javascript 版本

This commit is contained in:
Jamcy123
2022-04-12 16:57:25 +08:00
parent 7ba1a67c86
commit ae38a29068

View File

@ -166,20 +166,19 @@ JavaScript:
* @return {number[]} * @return {number[]}
*/ */
var nextGreaterElements = function (nums) { var nextGreaterElements = function (nums) {
// let map = new Map(); const len = nums.length;
let stack = []; let stack = [];
let res = new Array(nums.length).fill(-1); let res = Array(len).fill(-1);
for (let i = 0; i < nums.length * 2; i++) { for (let i = 0; i < len * 2; i++) {
while ( while (
stack.length && stack.length &&
nums[i % nums.length] > nums[stack[stack.length - 1]] nums[i % len] > nums[stack[stack.length - 1]]
) { ) {
let index = stack.pop(); const index = stack.pop();
res[index] = nums[i % nums.length]; res[index] = nums[i % len];
} }
stack.push(i % nums.length); stack.push(i % len);
} }
return res; return res;
}; };
``` ```