From 4a257c407660ec28cbf7b8a00c771f22cfc17a60 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 5 Apr 2024 11:18:42 +0800 Subject: [PATCH] 20240405 Finished --- src/problem/mod.rs | 3 +- ..._remove_duplicates_from_sorted_array_ii.rs | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 src/problem/p80_remove_duplicates_from_sorted_array_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index a015793..fc2ad03 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -93,4 +93,5 @@ mod p2952_minimum_number_of_coins_to_be_added; mod p331_verify_preorder_serialization_of_a_binary_tree; mod p88_merge_sorted_array; mod p26_remove_duplicates_from_sorted_array; -mod p27_remove_element; \ No newline at end of file +mod p27_remove_element; +mod p80_remove_duplicates_from_sorted_array_ii; \ No newline at end of file diff --git a/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs b/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs new file mode 100644 index 0000000..c34a85a --- /dev/null +++ b/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs @@ -0,0 +1,45 @@ +/** + * [80] Remove Duplicates from Sorted Array II + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut now = 1; + let mut count = 1; + + for i in 1..nums.len() { + if nums[i - 1] != nums[i] { + count = 1; + nums[now] = nums[i]; + now += 1; + } else { + if count < 2 { + nums[now] = nums[i]; + now += 1; + } + + count += 1; + } + } + + now as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_80() { + let mut nums = vec![1,1,1,2,2,3]; + assert_eq!(5, Solution::remove_duplicates(&mut nums)); + assert_eq!(vec![1,1,2,2,3,3], nums); + } +}