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.
本题解决基本思想类似于冒泡排序:
- 从数组尾部向前搜索,找到第一个0;
- 将0与后一位非0数字相交换
- 交换时,后面一位若为0,则表示后面的已经是换好的0数组了,不需再移位。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int i=nums.size()-1;i>=0;i--)
{
if(nums[i]==0)<span style="white-space:pre"> </span>//找到0元素,进行交换
{
for(int j=i;j<nums.size()-1;j++)
{
if(nums[j+1]!=0)
{
int temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
}
}
}
}
}
};