283. Move Zeroes
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 can_move = 0;
while (can_move < nums.size())
{
while (can_move < nums.size() && nums[can_move] != 0) //先找到首个可以移动的0的位置
can_move++;
for (int j = can_move + 1; j < nums.size(); j++) //再在0之后找到首个非0 来交换
{
if (nums[j] != 0)
{
swap(nums[can_move], nums[j]);
break;
}
}
can_move++;
}
}
};