xinyu04

导航

LeetCode 283 Move Zeroes

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Solution

点击查看代码
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int i=0,j=1;
        while(j<nums.size()){
            if(nums[i]==0 && nums[j]!=0){
                swap(nums[i], nums[j]);
                i++; j++;
            }
            else if(nums[i]==0 && nums[j]==0)j++;
            else{
                i++;j++;
            }
        }
    }
};

posted on 2022-11-03 16:23  Blackzxy  阅读(14)  评论(0编辑  收藏  举报