27. 移除元素

24 阅读1分钟
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i = 0;
        for (const int num : nums) {
            if (num != val) {
                nums[i++] = num;
            }
        }
        return i;
    }
};
impl Solution {
    pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 {
        let mut i = 0;
        for j in 0..nums.len() {
            if nums[j] != val {
                nums[i] = nums[j];
                i += 1;
            }
        }
        i as i32
    }
}