Skip to content

Commit

Permalink
Add problem 1920: Build Array from Permutation
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 31, 2023
1 parent 0c079b9 commit 242aff3
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
21 changes: 21 additions & 0 deletions src/problem_1920_build_array_from_permutation/mod.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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>();
}
}

0 comments on commit 242aff3

Please sign in to comment.