LeetCode 496. Next Greater Element I

Problem Statement



use std::collections::{HashMap, VecDeque};
impl Solution {
pub fn next_greater_element(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut ans = vec![];
let mut stack: Vec<i32> = vec![];
let mut m = HashMap::new();

for num in nums2 {
while !stack.is_empty() {
let cur = stack.last().unwrap().clone();
if cur >= num {
break;
}

m.entry(cur).or_insert(0);
*m.get_mut(&cur).unwrap() = num;
stack.pop();
}
stack.push(num);
}

for num in nums1 {
if m.contains_key(&num) {
ans.push(*m.get(&num).unwrap());
} else {
ans.push(-1);
}
}
return ans;
}
}