Java Solution with Generalized k


  • 1
    A

    General solution for k repetition; In this case, k=2.

    public int removeDuplicates(int[] A) {
        final int k = 2;
        if (A == null || A.length <= k)
            return A.length;
    
        int left = k; // left: next index to place; right: next element to check
        for (int right = k; right < A.length; right++) {
            for (int i = 1; i <= k; i++) {
                if (A[right] != A[left-i]) {
                    A[left++] = A[right];
                    break;
                }
            }
        }
        
        return left;
    }

  • 0
    S

    Thanks for sharing. Great idea!


Log in to reply
 

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