My Java Solution


  • 3
    A
        public class Solution {
        public void moveZeroes(int[] nums) {
            int zero = 0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]==0){
                    zero++;
                    continue;
                }
                nums[i-zero] = nums[i];
            }
            for(int i=nums.length-zero;i<nums.length;i++){
                nums[i] = 0;
            }
        }
    }

  • 0
    S

    no need to track zeros, just update zeros at the end:

    public class Solution {
    public void moveZeroes(int[] nums) {
    int curPos = 0;
    for (int i=0; i< nums.length; i++) {
    if (nums[i] != 0) { nums[curPos++] = nums[i]; }
    }
    while (curPos < nums.length) {
    nums[curPos++] = 0;
    }
    }
    }


  • 0
    A

    Thanks for StephenJ's Solution

     public class Solution { 
         public void moveZeroes(int[] nums) { 
            int curPos = 0; 
            for (int i=0; i< nums.length; i++) 
            { 
                if (nums[i] != 0) { 
                    nums[curPos++] = nums[i]; 
                } 
            } 
                while (curPos < nums.length) { 
                    nums[curPos++] = 0; 
                } 
            } 
        }

Log in to reply
 

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