解法一
swap all the non-zero element to the front
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int i=0, j=0;i<nums.size();i++){
if(nums[i]){
swap(nums[i], nums[j++]);
}
}
}
};
解法二 Two Pointers
1.swap when l points to zero and r points to non-zero
2.r runs faster than l, so r always points to a non-zero after l
class Solution {
public:
void moveZeroes(vector<int> &nums) {
int n = nums.size();
int l=0, r=0;
while(r<n){
if(nums[l]!=0) l++;
else if(nums[r]!=0) swap(nums[l++], nums[r]);
r++;
}
}
};