5-lines O(n) Java solution with no swapping


  • 9

    Explanation

    The basic idea is to save all none-zero numbers in place in the front part, then fill 0 into the remaining part. No need to swap in this way. Any advice will be welcome!

    public void moveZeroes(int[] nums) {
        int p = 0;// Index of none-zero number
        for (int i : nums) 
            if (i != 0) 
              nums[p++] = i;
        while (p < nums.length) nums[p++] = 0;
    }

  • 0
    X

    so cool!!!!!!!!!!!!!!!!!!!!!!


  • 0

    Thanks, just made some attempts before the final version ;)


  • 0
    D
    This post is deleted!

  • 0
    D

    this only works for java. for c++ it;s not working. And actually you are copying to a new array.


  • 0
    S

    good solution,but you swap the num at nums[p++] = i;


  • 0
    S

    yes,in someway,you are right.


  • 0

    Thanks, sjysimon, swap means exchange two numbers. In this way, we only need to fill in one number.


  • 0
    H

    Say this array is super long and contains all zeros.
    Then your algorithm will scan this array two times.
    While algorithm with swap() will guarantee to finish the work with one scan of array


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.