From 507dcb481564f82ae59c6bda69db4107e574ff22 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 3 Apr 2024 10:10:05 +0800 Subject: [PATCH] 20240403 Finished --- src/problem/mod.rs | 3 +- src/problem/p27_remove_element.rs | 52 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/problem/p27_remove_element.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4ccf9be..c326f36 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -91,4 +91,5 @@ mod p1997_first_day_where_you_have_been_in_all_the_rooms; mod p2908_minimum_sum_of_mountain_triplets_i; mod p2952_minimum_number_of_coins_to_be_added; mod p331_verify_preorder_serialization_of_a_binary_tree; -mod p88_merge_sorted_array; \ No newline at end of file +mod p88_merge_sorted_array; +mod p27_remove_element; \ No newline at end of file diff --git a/src/problem/p27_remove_element.rs b/src/problem/p27_remove_element.rs new file mode 100644 index 0000000..71d0de7 --- /dev/null +++ b/src/problem/p27_remove_element.rs @@ -0,0 +1,52 @@ +/** + * [27] Remove Element + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { + if nums.len() == 0 { + return 0; + } + + let mut last = nums.len() - 1; + let mut i = 0; + + while i <= last { + while nums[i] == val { + if i == last { + return last as i32; + } + + nums[i] = nums[last]; + last -= 1; + } + + i += 1; + } + + (last + 1) as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_27() { + let mut array = vec![3,2,2,3]; + assert_eq!(2, Solution::remove_element(&mut array, 3)); + for i in 0..2 { + assert_eq!(2, array[i]); + } + + let mut array = vec![3]; + assert_eq!(0, Solution::remove_element(&mut array, 3)); + } +}