一个数组,找出每个数组元素右侧第一个比当前数大的数的下标,时间复杂度O(N)
Sunny-117 opened this issue · comments
一个数组,找出每个数组元素右侧第一个比当前数大的数的下标,时间复杂度O(N)
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);
单调栈
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;
}
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]
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
}