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.
tips:不难是不难,就是思路开始出现了偏差,采用基本的移位覆盖,结果没有考虑到移位后数组如何还存在0的话,会有很大的差错,尝试改进之后顺利完成。
代码
public class Solution {
public void moveZeroes(int[] nums) {
int count=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]==0)
{
count++;
}
else
nums[i-count]=nums[i];
}
for(int i=nums.length-1;i>=nums.length-count;i--)
{
nums[i]=0;
}
}
}
414





