Easy Understand 2 pointers Java solution


  • 0
    R

    We keep two pointers, 1st for normal for loop to iterate through the array.
    2nd is to track the position of first 0 in the array.
    Keep exchanging non zero value with first 0 till the end of loop.

    public class Solution {
        public void moveZeroes(int[] nums) {
            int index=-1;//index to track 1st 0  in the array
            int count = 0;
            for(int i=0;i<nums.length;i++){
                if(index==-1&&nums[i]==0){ index = i;}//find 1st 0 for the 1st time only
                if(index!=i &&nums[i]==0){count++;}//count the number consecutive 0
                if(index!=-1&&i>index&&nums[i]!=0){
                    nums[index] = nums[i];
                    nums[i]=0;
                    index = i;
                    index = i-count;//need to move back 'count' times to to the position of first 0
                }
            }
        }
    }
    

Log in to reply
 

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