From 5f7bc37f2e125543bbe7164108f61b14aa917e2f Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Thu, 7 Dec 2023 08:46:13 +0800 Subject: [PATCH] leetcode: Add remove-element --- Cargo.lock | 4 ++++ leetcode/0027.remove-element/Cargo.toml | 7 ++++++ leetcode/0027.remove-element/src/main.rs | 29 ++++++++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 leetcode/0027.remove-element/Cargo.toml create mode 100644 leetcode/0027.remove-element/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 3d0034ec..97548b77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -342,6 +342,10 @@ version = "0.1.0" name = "lc-0026-remove-duplicates-from-sorted-array" version = "0.1.0" +[[package]] +name = "lc-0027-remove-element" +version = "0.1.0" + [[package]] name = "lc-0053-maximum-subarray" version = "0.1.0" diff --git a/leetcode/0027.remove-element/Cargo.toml b/leetcode/0027.remove-element/Cargo.toml new file mode 100644 index 00000000..8d776fbd --- /dev/null +++ b/leetcode/0027.remove-element/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0027-remove-element" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/leetcode/0027.remove-element/src/main.rs b/leetcode/0027.remove-element/src/main.rs new file mode 100644 index 00000000..3a953494 --- /dev/null +++ b/leetcode/0027.remove-element/src/main.rs @@ -0,0 +1,29 @@ +// Copyright (c) 2023 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be +// found in the LICENSE file. + +pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { + let mut i = 0; + while i < nums.len() { + if nums[i] == val { + nums.swap_remove(i); + } else { + i += 1; + } + } + nums.len() as i32 +} + +fn main() { + let mut nums = vec![3, 2, 2, 3]; + let val = 3; + let len = remove_element(&mut nums, val); + assert_eq!(len, 2); + assert_eq!(nums, vec![2, 2]); + + let mut nums = vec![0, 1, 2, 2, 3, 0, 4, 2]; + let val = 2; + let len = remove_element(&mut nums, val); + assert_eq!(len, 5); + assert_eq!(nums, vec![0, 1, 4, 0, 3]); +}