Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

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);

单调栈

@veneno-o
Copy link
Contributor

veneno-o commented Mar 11, 2023

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;
}

@kangkang123269
Copy link

kangkang123269 commented Sep 11, 2023

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]

@gswysy
Copy link

gswysy commented Feb 29, 2024

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants