https://leetcode.com/problems/next-greater-element-ii/description/
vector<int> nextGreaterElements(vector<int>& nums) {
int N = nums.size();
vector<int> res(N, -1);
if(N < 2) return res;
stack<int> st;
st.push(0);
//int bot = 0;
for(int i=1; i<N*2; i++) {
int num = nums[i%N];
while(!st.empty() && nums[st.top()]<num) {
res[st.top()] = num;
st.pop();
}
//if(st.empty()) bot = i;
if(i<N) st.push(i);
}
return res;
}
or, change the upper bound for the loop when i>=N
vector<int> nextGreaterElements(vector<int>& nums) {
int N = nums.size();
vector<int> res(N, -1);
if(N < 2) return res;
stack<int> st;
st.push(0);
int bot = 0;
for(int i=1; i<N+bot+1; i++) {
int num = nums[i%N];
while(!st.empty() && nums[st.top()]<num) {
res[st.top()] = num;
st.pop();
}
if(st.empty()) bot = i;
if(i<N) st.push(i);
}
return res;
}
No comments:
Post a Comment