在 JavaScript 中使用堆栈查找下一个更大元素

问题描述 投票:0回答:1

我正在熟悉 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
}

我知道我已经非常接近了,但我无法想出满足所有情况的解决方案,如果有人能指出我正确的方向,我将不胜感激

javascript stack
1个回答
0
投票

我会从末尾循环数组,它看起来更自然,因为我们分析了每个数组项的数组的其余部分。

console.log(...greaterL([56, 23, 1, 5, 18, 17]))//[-1, -1, 5, 18, -1, -1]

function greaterL(arr){
  
  let stack = [arr[arr.length - 1]];
  const result = [-1];
  
  for(let i = arr.length - 2; i >= 0; i--){
    const item = arr[i];
    const found = stack.find(max => max > item);
    result.unshift(found ?? -1);
    found === undefined ? stack = [item] : stack.unshift(item);
  }
  
  return result;
}

© www.soinside.com 2019 - 2024. All rights reserved.