Move Zeroes

2019-05-25 22:53:14 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int index = 0;
        for(int i = 0; i < nums.size(); i  ) {
            if(nums[i] != 0) {
                nums[index] = nums[i];
                index  ;
            }
        }
        for(int i = nums.size() - 1; i > index - 1; i--) {
            nums[i] = 0;
        }
    }
};
  • Version 2
代码语言:javascript复制
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int index = 0;
        for(int i = 0; i < nums.size(); i  ) {
            if(nums[i] != 0) {
                swap(nums[i], nums[index]);
                index  ;
            }
        }
    }

private:
    void swap(int& a, int& b) {
        int temp = a;
        a = b;
        b = temp;
    }
};

0 人点赞