参考学习:单调栈结构解决三道算法题 :: labuladong的算法小抄
单调栈模板:
vector<int> nextGreaterElement(vector<int> nums) {
int sz = nums.size();
stack<int> stk;
for (int i = sz - 1; i >= 0; --i) {
while (!stk.empty() && stk.top() <= nums[i) {
stk.pop();
}
res[i] = stk.empty() ? -1 : stk.top();
stk.push(nums[i]);
}
return res;
}
个人理解:
使用栈从后向前遍历题目所给数组,对遍历到的每个元素进行判断,当前栈若是非空且该元素大于栈顶元素,则弹出栈顶元素,在此重复上一操作;直至栈为空(说明数组中没有比该元素还大的元素)就将该元素的res数组幅值为-1;或遇到大于该元素的栈顶元素,就将栈顶元素赋值到res数组中。
力扣 503下一个更大元素

代码:
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int sz = nums.size();
vector<int> res(sz);
stack<int> stk;
for (int i = sz - 1; i >= 0; --i) {
stk.push(nums[i]);
}
for (int i = sz - 1; i >= 0; --i) {
while (!stk.empty() && stk.top() <= nums[i]) {
stk.pop();
}
res[i] = stk.empty() ? -1 : stk.top();
stk.push(nums[i]);
}
return res;
}
};
文章介绍了如何使用单调栈解决查找数组中下一个更大元素的算法问题,提供了一个具体的模板代码示例,并解释了代码逻辑,涉及力扣503题的解法。
1109

被折叠的 条评论
为什么被折叠?



