我正在熟悉Stack,虽然我能够想出一种逻辑,使我在大多数情况下都有问题,但我遇到的问题很少.
console.log(greaterL([56, 23, 1, 5, 18, 17]))//[-1, -1, 5, 18, -1, -1]
====> actually returns -1, 5, 18, -1, -1, -1
console.log(greaterL([70, 60, 1, 4, 8, 12, 50, 23]))//[-1,-1, 4, 8, 12, 50, -1, -1]
====> actually returns -1, 4, 8,12, 50, -1, -1, -1
function greaterL(arr){
let stack = []
let result = []
for(let i = 0; i < arr.length-1; i++){
stack.push(arr[i])
let next = arr[i+1]
while(stack.length!==0 && stack[stack.length-1] < next){
stack.pop();
result.push(next);
}
}
result.push(-1)
while(stack.length){
let value = stack.pop()
if(arr[0]===value){
result.unshift(-1)
}else{
result.push(-1)
}
}
return result
}
我知道我已经很接近了,但我不能想出一个能满足所有情况的解决方案,如果有人能为我指出正确的方向,我将不胜感激