503. 下一个更大元素 II
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
- 拼接两个数组,扩充nums
- 遍历的过程中模拟走两遍nums
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
st.push(0);
for(int i = 1; i < n * 2; i++){
while(!st.empty() && nums[i % n] > nums[st.top()]){
res[st.top()] = nums[i % n];
st.pop();
}
st.push(i % n);
}
return res;
}
};