Leecode no.283 移动零

package leecode;

/**
* 283. 移动零
* 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序
*
* @author Tang
* @date 2021/10/22
*/
public class MoveZeroes {

/**
* 利用双指针
* 快指针顺序遍历数组
* 每次遍历到的元素判断是否为0,如果不是0 则慢指针++,
* 如果是0 慢指针元素等于快指针元素(此时慢指针的元素指的是0元素,把快指针的正常元素换过来)
*
* @param nums
*/
public void moveZeroes(int[] nums) {
int slow = 0;
int fast = 0;
while(fast < nums.length) {
if(nums[fast] == 0) {
fast++;
continue;
}
int temp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = temp;
fast++;
slow++;
}

}

public static void main(String[] args) {
int[] nums = {1};
new MoveZeroes().moveZeroes(nums);
}

}
原文地址:https://www.cnblogs.com/ttaall/p/15439573.html