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.
Example:
Input: [0,1,0,3,12]
Output: [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.
把0放最后,并保证非零元素的相对顺序。直接计算出0的数量count
,然后用一个指针指向当前插入的位置,将非零元素依次填充进去。最后,再从后开始,将最后count
个元素直接抹成0.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int count = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] == 0)
count++;
}
int start = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] != 0)
{
nums[start] = nums[i];
start++;
}
}
int end = nums.size() - 1;
while(count--)
nums[end--] = 0;
}
};