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;
}
};