diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 00d367e..9a16d98 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -488,3 +488,5 @@ mod p1742_maximum_number_of_balls_in_a_box; mod p1552_magnetic_force_between_two_balls; mod p1706_where_will_the_ball_fall; + +mod p1299_replace_elements_with_greatest_element_on_right_side; diff --git a/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs b/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs new file mode 100644 index 0000000..597e310 --- /dev/null +++ b/src/problem/p1299_replace_elements_with_greatest_element_on_right_side.rs @@ -0,0 +1,49 @@ +/** + * [1299] Replace Elements with Greatest Element on Right Side + */ +pub struct Solution {} + +// submission codes start here +use std::collections::BinaryHeap; +use std::iter::FromIterator; + +impl Solution { + pub fn replace_elements(arr: Vec) -> Vec { + let mut heap: BinaryHeap<(i32, usize)> = + BinaryHeap::from_iter(arr[1..].into_iter().enumerate().map(|(i, v)| (*v, i + 1))); + + let mut result = Vec::with_capacity(arr.len()); + + for i in 0..arr.len() - 1 { + while let Some(head) = heap.peek() { + if head.1 > i { + break; + } + + heap.pop(); + } + if let Some(head) = heap.peek() { + result.push(head.0); + } + } + + result.push(-1); + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1299() { + assert_eq!( + vec![18, 6, 6, 6, 1, -1], + Solution::replace_elements(vec![17, 18, 5, 4, 6, 1]) + ); + assert_eq!(vec![-1], Solution::replace_elements(vec![400])); + } +}