Skip to content

Commit

Permalink
Add problem 2295: Replace Elements in an Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 26, 2024
1 parent 430b3ac commit 4ba2413
Show file tree
Hide file tree
Showing 3 changed files with 74 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 @@ -1703,6 +1703,7 @@ pub mod problem_2287_rearrange_characters_to_make_target_string;
pub mod problem_2288_apply_discount_to_prices;
pub mod problem_2293_min_max_game;
pub mod problem_2294_partition_array_such_that_maximum_difference_is_k;
pub mod problem_2295_replace_elements_in_an_array;

#[cfg(test)]
mod test_utilities;
46 changes: 46 additions & 0 deletions src/problem_2295_replace_elements_in_an_array/hash_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::collections::HashMap;

impl Solution {
pub fn array_change(nums: Vec<i32>, operations: Vec<Vec<i32>>) -> Vec<i32> {
let mut nums = nums;
let mut operations = operations;
let mut replacements = HashMap::new();

while let Some(operation) = operations.pop() {
let [from, to]: [_; 2] = operation.try_into().ok().unwrap();
let to = replacements.get(&to).copied().unwrap_or(to);

replacements.insert(from, to);
}

drop(operations);

for num in &mut nums {
if let Some(replacement) = replacements.get(num) {
*num = *replacement;
}
}

nums
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn array_change(nums: Vec<i32>, operations: Vec<Vec<i32>>) -> Vec<i32> {
Self::array_change(nums, operations)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
27 changes: 27 additions & 0 deletions src/problem_2295_replace_elements_in_an_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub mod hash_map;

pub trait Solution {
fn array_change(nums: Vec<i32>, operations: Vec<Vec<i32>>) -> Vec<i32>;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(
(&[1, 2, 4, 6] as &[_], &[[1, 3], [4, 7], [6, 1]] as &[_]),
&[3, 2, 7, 1] as &[_],
),
((&[1, 2], &[[1, 3], [2, 1], [3, 2]]), &[2, 1]),
];

for ((nums, operations), expected) in test_cases {
assert_eq!(
S::array_change(nums.to_vec(), operations.iter().map(Vec::from).collect()),
expected,
);
}
}
}

0 comments on commit 4ba2413

Please sign in to comment.