1 Line C++ Solution


  • 6
    P

    Only 1 line using STL

     return unique(A, A+n)-A;
    

    The unique algorithm record the positions of the unique elements, and then remove duplicates using unique_copy(). The above code has a 41 ms time cost.

    Below is my 33ms solution without STL.

    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
           int mark=1;
           for(int i=1;i<n;i++)
            {
                if(A[i]!=A[i-1])
                    A[mark++]=A[i];
            }
            return min(mark,n);
        }
    };

Log in to reply
 

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