C, 3mS, O(n), Generic


  • 0
    M

    Read offset (roff), write offset (wroff), duplicate count (cnt) and below mentioned two states:

    1. Duplicate count < 2 : Just copy elements from read to write offset
    2. Duplicate count > 2 : Move read offset until it's the end of duplicate sequence
    #define DUP_COUNT 2
    
    int removeDuplicates(int* a, int len)
    {
        int roff, wroff = 0, cnt = 0;
    
        /* Loop till the end of the array: Handle two states. */
        for (roff = 0; roff < len; ++roff) {
            /* 1. Duplicate count < DUP_COUNT -- Just Copy values and
                  identify duplicates. */
            if (cnt < DUP_COUNT) {
                a[wroff++] = a[roff];
                cnt = roff + 1 < len && a[roff] == a[roff + 1] ? cnt + 1 : 0; // duplicate?
            }
            /* 2. Avoid copy, identify the end of duplicate sequence. */
            else if (a[roff] != a[roff - 1]) {
                cnt = 0; // reset
                --roff; // compensate for the increment above
            }
        }
    
        /* Return */
        return wroff;
    }
    

Log in to reply
 

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