js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

一个数组,找出每个数组元素右侧第一个比当前数大的数的下标,时间复杂度O(N)

Open Sunny-117 opened this issue 3 years ago • 4 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

const num = [1, 3, 4, 2, 5, 6, 7];
const res = new Array(num.length).fill(-1);
const stk = [0];
for(let i = 1; i < num.length; i++){
    if(num[i] <= num[stk[stk.length-1]]) stk.push(i);
    else{
        while(stk.length && num[i] > num[stk[stk.length-1]]){
            let val = stk.pop();
            res[val] = i;
        }
        stk.push(i);
    }
}
console.log(res);

单调栈

bearki99 avatar Feb 13 '23 02:02 bearki99

function main(arr){
    if(arr.length < 2) return [];
    // 单调递减栈
    const stack = [arr[0]], res = [];
    for(let i = 1; i < arr.length; ++i){
        if(arr[i] > stack[stack.length - 1]){
            stack.push(arr[i]);
            res.push(arr[i]);
        }
    }
    return res;
}

veneno-o avatar Mar 11 '23 04:03 veneno-o

function nextGreaterElementIndex(nums) {
    let res = new Array(nums.length).fill(-1);
    let stack = []; // 这个栈用于保存元素索引

    for(let i=0; i<nums.length; i++) {
        while(stack.length > 0 && nums[stack[stack.length-1]] < nums[i]) {
            // 当前遍历到的数比栈顶元素大,那么就找到了比栈顶元素大的右侧第一个数
            let index = stack.pop();
            res[index] = i;
        }
        stack.push(i); // 将当前数入栈
    }

    return res;
}

console.log(nextGreaterElementIndex([2, 1, 2, 4, 3])); 
// 输出:[3, 2, 3, -1, -1]

kangkang123269 avatar Sep 11 '23 07:09 kangkang123269

function find(arr) {
  let stack = [0],
    res = new Array(arr.length).fill(-1)
  for (let i = 1; i < arr.length; i++) {
    while (stack.length && arr[i] > arr[stack[stack.length - 1]]) {
      res[stack.pop()] = arr[i]
    }
    stack.push(i)
  }
  return res
}

Aurora-GSW avatar Feb 29 '24 02:02 Aurora-GSW