Simple Java solution beats 96%


  • 0
    L

    Since there is no new allocation allowed, the idea is to use the same array. The next hint is that the array is sorted, so the duplicate elements will be subsequent. So if you skip duplicate elements, you will overwrite only those redundant values. Think two pointers: one moving ahead and skipping duplicates, another copies only non-duplicate values and then incremented.

    public int removeDuplicates(int[] nums) {
            int j=0; //j an index that keeps track of the unique elements.
            //i regular index that skips the duplicates.
            for(int i=0;i<nums.length;i++) {
                if(i>0 && nums[i] ==nums[i-1]) {
                    continue;
                }
                nums[j++]=nums[i];
            }
            return j;
        }
    

Log in to reply
 

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