Problem:
给一个整数数组,把数组中所有的0元素放在最后,其它元素的相对顺序不变。
Solution:
设置两个游标进行交换,在O(n)复杂度内解决。
notes:
remove和erase的方法详解:
//Solution1:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
fill(remove(nums.begin(), nums.end(), 0), nums.end(), 0);
}
};
//Solution2:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int idx = 0;
int idx_zero = 0;
while(idx < nums.size()) {
if(nums[idx] != 0) {
swap(nums[idx], nums[idx_zero]);
idx_zero++;
}
idx++;
}
}
};