Skip to content

Commit

Permalink
leetcode: Add remove-element
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 7, 2023
1 parent 617069b commit 5f7bc37
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions leetcode/0027.remove-element/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0027-remove-element"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
29 changes: 29 additions & 0 deletions leetcode/0027.remove-element/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. 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<i32>, 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]);
}

0 comments on commit 5f7bc37

Please sign in to comment.