-
Notifications
You must be signed in to change notification settings - Fork 1
/
no_503.rs
32 lines (27 loc) · 979 Bytes
/
no_503.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct Solution {}
impl Solution {
pub fn next_greater_elements(nums: Vec<i32>) -> Vec<i32> {
let mut stack: Vec<usize> = vec![];
let mut vector: Vec<i32> = vec![-1; nums.len()];
// push the first element
stack.push(0);
for i in 1..nums.len() * 2 {
let current_value = nums[i % nums.len()];
while !stack.is_empty() && current_value > nums[*stack.last().unwrap()] {
let t = stack.pop().unwrap();
vector[t] = current_value;
};
if i < nums.len() {
stack.push(i);
}
}
vector
}
}
#[test]
fn test() {
assert_eq!(Solution::next_greater_elements(vec![]), vec![]);
assert_eq!(Solution::next_greater_elements(vec![1]), vec![-1]);
assert_eq!(Solution::next_greater_elements(vec![1, 2, 1]), vec![2, -1, 2]);
assert_eq!(Solution::next_greater_elements(vec![1, 2, 3, 4, 3]), vec![2, 3, 4, -1, 4]);
}