Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.

Example:

Input:0.1.0.3.12] output: [1.3.12.0.0]
Copy the code

Description:

  • Must operate on the original array, cannot copy additional arrays.
  • Minimize the number of operations.

If you want to move all the zeros to the end of the array without caring about the position of the non-zero elements, you can use the Dutch flag problem to solve the problem, and the code is as follows:

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null) {return;
        }

        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            if(nums[left] == 0){ swap(nums, left, right--); } left++; }}public void swap(int[] nums, int i, int j){
        inttemp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }}Copy the code

But they want to make sure that the relative order of the non-zero elements doesn’t change, so that doesn’t guarantee anything. We can use the idea of fast and slow Pointers to move all the non-zero elements to the front of the array, and then set the rest of the non-zero elements to zero as follows:


The solution code is as follows:

class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null) {return;
        }
        int index = removeZero(nums, 0);
        for(int i = index; index < nums.length; index++){
            nums[index] = 0; }}public int removeZero(int[] nums, int val){
        int slow = 0;
        int fast = 0;
        while(fast < nums.length){
            if(nums[fast] ! = val){ nums[slow++] = nums[fast]; } fast++; }returnslow; }}Copy the code