Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
1.算法
void moveZeroes(vector<int>& nums) {
int m=0;
for(int i=0;i<nums.size();i++){
if(nums[i]==0) m++;
}
nums.erase(remove(nums.begin(),nums.end(),0),nums.end());
for(int j=0;j<m;j++){
nums.push_back(0);
}
}
2.erase和remove的使用
- erase()的作用是刪除掉某個位置position或一段區域(begin, end)中的元素,減少其size;
- remove()只是將待刪除元素之后的元素移動到vector的前端,而不是刪除。操作并不改變vector的size。若要真正移除,需要搭配使用erase()。
舉例:
原vector:{0,1,0,3,12}
使用remove(nums.begin(),nums.end(),0)
后 變為 [1,3,12,3,12];
簡要地說,remove移動指定區間中的元素直到所有“不刪除的”元素在區間的開頭(相對位置和原來它們的一樣)。它返回一個指向最后一個的下一個“不刪除的”元素的迭代器。返回值是區間的“新邏輯終點”;remove遍歷這個區間,把要“刪除的”值覆蓋為后面要保留的值。這個覆蓋通過對持有被覆蓋的值的元素賦值來完成。
至于操作后的結果是: “不刪除的”元素在v中的v.begin()和newEnd之間,“刪除的”元素就必須在newEnd和v.end()之間——這好像很合理。事實上不是這樣。
- 要正真刪除東西的話,你應該在remove后面接上erase,就如上面
nums.erase(remove(nums.begin(),nums.end(),0),nums.end());