如果不看tag肯定想不到可以用two pointers很快很巧妙的做出来!
最开始的navie想法
void moveZeroes(vector<int>& nums) {
//delte all zeroes and then add back at the end
int cnt = 0;
for (auto it = nums.begin(); it != nums.end(); ) {
if (*it == 0) {
it = nums.erase(it);
++cnt;
}
else {
++it;
}
}
while (cnt--) {
nums.push_back(0);
}
}
巧妙的two pointers做法(乍一看可能有点迷糊, 举个小例子演算下就能清楚了)
void moveZeroes(vector<int>& nums) {
for (int lastZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++) {
if (nums[cur] != 0) {
swap(nums[lastZeroFoundAt++], nums[cur]);
}
}
}