移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
2.快慢指针
使用两个指针,慢指针前面都是非零元素,快指针寻找下一个非零元素。
class Solution {
public void moveZeroes(int[] nums) {
int i=0,j=1;
while(i<nums.length)
{
if(nums[i]!=0)
{
i++;j++;
}
}
while(j<nums.length)
{
if(nums[j]==0)
j++;
else {
nums[i++]=nums[j];
nums[j]=0;
j++;
}
}
}
}
一个巧妙的解法:统计该数前面0的个数,然后将这个数向前移动相应位置,最后在空出的位置补0
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-count;i<nums.length;i++)
{
nums[i]=0;
}
}
}