Simple Java 1ms solution with explaination


  • 0
    S
    // What the code does is that it has 2 pointers. first pointer points to a new number.
    // The second pointer traverses over the numbers following the first pointer until they are same.
    // Now if the difference between these pointers increases beyond 1
    // the code neglects these successive same number and when a greater
    // number is encountered first pointer is pointed to that number and second pointer
    // iterates over the successive numbers similarly as before.
    // Count variable tracks times when first pointer changes and if next number is same
    // or not and modifies the array in-place accordingly.
    
    public int removeDuplicates(int[] nums) {
                    if(nums.length <= 1)
                        return nums.length;
                    int length = nums.length;
                    int pointer1=0;
                    int pointer2=1;
                    int count=1;
                    while(pointer2<length){
                        if(nums[pointer2]==nums[pointer1]){
                            if((pointer2-pointer1)<2){
                                nums[count] = nums[pointer1];
                                count++;
                            }
                            pointer2++;
                        }
                        else{
                            pointer1=pointer2;
                            pointer2++;
                            nums[count] = nums[pointer1];
                            count++;
                        }
                    }
                    return count;
                }

Log in to reply
 

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