Total Accepted: 23568
Total Submissions: 56984
Difficulty: Easy
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]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int iZeroNum = 0;//find zero num
int iFirstZeroPosition = 0;
bool bFirstFindZero = false;
for(vector<int>::iterator iter = nums.begin() ; iter != nums.end(); iter++)
{
if( *iter == 0 )
{
iZeroNum++;
if(!bFirstFindZero)//如果是第一次发现0
{
bFirstFindZero = true;
iFirstZeroPosition = iter - nums.begin();
}
}
else
{
if(bFirstFindZero)
std::swap(*iter,*(nums.begin() + iFirstZeroPosition));
if(iZeroNum > 1)
{
iFirstZeroPosition++;
}
else
iFirstZeroPosition = iter - nums.begin();
}
}
}
};