LeetCode Hot 100复习 移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

class Solution {
public:
    void moveZeroes(vector& nums) {
        int n = nums.size();
        int left = 0;
        int right = 0;
        while(right < n)
        {
            if(nums[right])
            {
                swap(nums[right],nums[left]);
                left++;

            }
            right++;
        }
        
    }
};

你可能感兴趣的:(leetcode,算法)