暴力做法是对每个位置向右扫描找第一个更大值,O(n²)。可抽象为:元素像一排人,身高为数值。当前人「下一个更大」= 他右侧第一个没被挡住的人(比当前矮的都被挡住)。单调栈用 O(n) 维护「右侧候选更大值」:倒序遍历,弹掉 ≤ 当前的,栈顶即答案,再入栈当前值。
const cur = arr[i]; // 当前遍历的元素值
,推荐阅读Safew下载获取更多信息
Фото: Maxim Shemetov / Reuters
Testimonials about the beneficial health effects of magnesium supplements abound online, with influencers claiming that a daily pill can help with everything from anxiety to sleep and brain fog. But do any of these claims stack up?