diff --git a/src/lib.rs b/src/lib.rs index f6616530..b63c455d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1463,6 +1463,7 @@ pub mod problem_1909_remove_one_element_to_make_the_array_strictly_increasing; pub mod problem_1911_maximum_alternating_subsequence_sum; pub mod problem_1913_maximum_product_difference_between_two_pairs; pub mod problem_1915_number_of_wonderful_substrings; +pub mod problem_1920_build_array_from_permutation; #[cfg(test)] mod test_utilities; diff --git a/src/problem_1920_build_array_from_permutation/mod.rs b/src/problem_1920_build_array_from_permutation/mod.rs new file mode 100644 index 00000000..677bad89 --- /dev/null +++ b/src/problem_1920_build_array_from_permutation/mod.rs @@ -0,0 +1,21 @@ +pub mod utilize_higher_bits; + +pub trait Solution { + fn build_array(nums: Vec<i32>) -> Vec<i32>; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run<S: Solution>() { + let test_cases = [ + (&[0, 2, 1, 5, 3, 4] as &[_], &[0, 1, 2, 4, 5, 3] as &[_]), + (&[5, 0, 1, 2, 3, 4], &[4, 5, 0, 1, 2, 3]), + ]; + + for (nums, expected) in test_cases { + assert_eq!(S::build_array(nums.to_vec()), expected); + } + } +} diff --git a/src/problem_1920_build_array_from_permutation/utilize_higher_bits.rs b/src/problem_1920_build_array_from_permutation/utilize_higher_bits.rs new file mode 100644 index 00000000..d70fe056 --- /dev/null +++ b/src/problem_1920_build_array_from_permutation/utilize_higher_bits.rs @@ -0,0 +1,37 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn build_array(nums: Vec<i32>) -> Vec<i32> { + let mut nums = nums; + let slice = nums.as_mut_slice(); + + for i in 0..slice.len() { + slice[i] |= slice[slice[i] as u32 as usize] << 16; + } + + for num in slice { + *num >>= 16; + *num &= 0x_ffff; + } + + nums + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn build_array(nums: Vec<i32>) -> Vec<i32> { + Self::build_array(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::<super::Solution>(); + } +}