[LeetCode] Next Greater Element II

503. Next Greater Element II

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, return -1 for this number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int sz = nums.size();
vector<int> res(sz, -1);
stack<int> st;
for(int i = 0; i < sz<<1; i++) {
while(st.size() && nums[st.top()] < nums[i % sz]) {
res[st.top()] = nums[i % sz];
st.pop();
}
st.push(i % sz);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/next-greater-element-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.