题目: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.
解答:在处理这个题的时候想到了快排中一遍扫描的过程,利用两个变量i和j,分别来控制0的边界和非0的边界。故而可以得到如下的代码:
代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int size = nums.size();
if(size > 0)
{
int i = 0,j = 0;
while((i < size) && (j < size))
{
while((i < size) && (nums[i] != 0))
{
i++;
}
j = i;
while((j < size) && (nums[j]) == 0)
{
j++;
}
if(j >= size)
break;
nums[i] = nums[j];
nums[j] = 0;
i++;
}
}
}
};