Java Single Loop Accepted Simple Solution


  • 0
    V
    public void moveZeroes(int[] nums) {
            int pointer = 0;
            for (int i = 0; i < nums.length; i++) {
                if(nums[i] != 0) {
                    nums[pointer] = nums[i];
                    if(i != pointer) nums[i] = 0;
                    pointer++;
                }
            }
        }

  • 0
    Z

    actually in line 6, it is if(i != pointer) :)
    But brilliant idea, thanks a lot


  • 0
    H

    First, this is not really single pointer, because you have "pointer" and "i" two pointers.

    Second, I copied this code to the tester but it doesn't pass the test. You have this line "if(i != i) nums[i] = 0;". "(i != i)" is always true. You mush have messed up something.


  • 0
    V

    Oh yeah. Thank you so much. I have messed it while copying. Fixed it :)


  • 0
    V

    Oh yeah. Thank you so much. I have messed it while copying. Fixed it :)


Log in to reply
 

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