LeetCode 503. Next Greater Element II

Problem Statement


impl Solution {
pub fn next_greater_elements(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut ans = vec![-1; n];
let mut stack: Vec<usize> = vec![];

for i in 0..2 * n {
let num = nums[i % n];
while !stack.is_empty() {
let top = stack.last().unwrap().clone();
if nums[top] >= num {
break;
}
ans[top] = num;
stack.pop();
}
if i < n {
stack.push(i);
}
}

return ans;
}
}