Simple java solution with explanation


  • 4
    H
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) {return 0;}
        int pointer = 0, flag = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1] && flag == 0) {
                flag = 1;
                pointer++;
            } else if (nums[i] != nums[i - 1]) {
                flag = 0;
                pointer++;
            }
            nums[pointer] = nums[i];
        }
        return pointer + 1;
    }
    

    The variable flag is to show if this number (nums[i]) has appeared more or equals to third times. The variable pointer is the location that each number (nums[i]) should appeared in. The special case is when the array is empty.


Log in to reply
 

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