283_move_zero

Leetcode

283.移动零

shaozkshaozk leetcode/283_move_zero.cpp · 15 行 · 更新于 2026-09-08

// 283.移动零
// 
// 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
// 请注意 ,必须在不复制数组的情况下原地对数组进行操作。

void moveZeroes(vector<int>& nums) {
    int fast = 0, slow = 0;
    while (fast < nums.size()) {
        if (nums[fast]) {
            swap(nums[fast], nums[slow]);
            ++slow;
        } 
        ++fast;
    }
}

评论