I know this way is very slow, but in this way, It cannot even print a nums array out. Why?

  • 0
    public void moveZeroes2(int[] nums) {      
         if(nums==null || nums.length==1) {
         for(int i=0; i<nums.length-1;i++) {
              for(int j=i; j<nums.length-1; j++) {
                  nums[j] = nums[j+1];

  • 1

    Hi - Hope this helps :)

    1. Just in case having any problems with submission, method is named moveZeroes2 (incorrect) instead of moveZeroes (correct).

    2. Right after "nums[nums.length-1]=0;" , there is a line with "i--;" which makes it so the variable i does not increment and the loop never breaks.

    3. Still, if removing or commenting the i-- line, the code would not work for cases like [0,0,1].

    • For nums array of [0,0,1], on first iteration (when i == 0), inside of inner loop, nums[2] gets assigned value of 1, later nums[3] is assigned 0, and the nums array becomes [0,1,0]. One last iteration occurs where i == 1 and nums[1] == 1. Since 1 != 0, nothing occurs at this point. Outer loop breaks after this.
    1. There are other really good working solutions in discussion. Could show some of them here but am afraid it might be a spoiler if you are enjoying figuring out.

Log in to reply

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