-
-
Notifications
You must be signed in to change notification settings - Fork 241
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
Comments
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] |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: