LintCode-[容易]539.移動ゼロ
説明:
1つの配列numsに関数を書いて0を配列の一番後ろに移動し、ゼロでない要素は元の配列の順序を維持します.
注意事項:
1.元の配列で操作する必要がある.オペランドの最小化
サンプル:
nums=[0,1,0,3,12]を与え、関数を呼び出した後、nums=[1,3,12,0,0]を与える.
考え方:
ベクトルを1回巡り、すべての0項目を削除し、0の個数を記録し、最後にベクトルの後ろにこの数の0を加えます.
C++実装:
1つの配列numsに関数を書いて0を配列の一番後ろに移動し、ゼロでない要素は元の配列の順序を維持します.
注意事項:
1.元の配列で操作する必要がある.オペランドの最小化
サンプル:
nums=[0,1,0,3,12]を与え、関数を呼び出した後、nums=[1,3,12,0,0]を与える.
考え方:
ベクトルを1回巡り、すべての0項目を削除し、0の個数を記録し、最後にベクトルの後ろにこの数の0を加えます.
C++実装:
class Solution {
public:
/**
* @param nums an integer array
* @return nothing, do this in-place
*/
void moveZeroes(vector<int>& nums) {
// Write your code
vector<int>::iterator it;
int count = 0;
for (it = nums.begin(); it != nums.end(); ) {
if ((*it) == 0) {
count++;
it = nums.erase(it);
}
else {
it++;
}
}
for (int i = 0; i < count; i++) {
nums.push_back(0);
}
}
};