My Java Solution, easy to understand, extend to k duplicates with explanation


  • 1
    public int removeDuplicates(int[] A) {
        if (A == null || A.length == 0) {
            return 0;
        }
        int count = 0; // counter of accepted numbers
        int duplicate = 1; //counter of current duplicates
        for (int i = 1; i < A.length; i++) {
            if (A[i] != A[count]) {
                count++;
                A[count] = A[i];
                duplicate = 1;
            } else {
                if (duplicate < 2) { // where apply to k duplicates
                    count++;
                    A[count] = A[i];
                    duplicate++;
                }
            }
        }
        return count+1;
    }

Log in to reply
 

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