Extremely simple java solution with comments


  • -2
    D

    public int removeDuplicates(int[] nums) {

        //if no elements in the array return 0
        if(nums==null || nums.length==0)
            return 0;
        //if only 1 element present return
        if(nums.length==1)
            return 1;
            
        //variable to keep track of unique elements
        int k=1;
        
        for(int i=1;i<nums.length;i++)
        {
            //skip duplicate elements
            if(nums[i]!=nums[i-1])
                nums[k++]=nums[i];
            
        }
        
        //'k' keeps track of the new length after removing duplicates
        return k;
        
    }

  • 0
    D

    Dude, the array has been sorted.


  • 0
    D

    alright, this helps in the case its not sorted, just ignore the line, thats it!


Log in to reply
 

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