My accepted O(n) and constant space solution,Any advising?


  • 0
    K
    class Solution {
    public:
        int removeDuplicates(int A[], int n) 
        {
            int start=1;
            int freeLen=0;
            for(int i=1;i<n;i++)
            {
                if(A[i]==A[i-1])
                {
                    start=i-freeLen;
                    freeLen++;
                }
                else
                {
                    A[start]=A[i];
                    start=i-freeLen+1;
                }
                    
            }
            return (n-freeLen);
        }
    };

  • 3
    J

    start is not nesserary.

    int removeDuplicates(int A[], int n) {
        int move = 0;
        
        for(int i=1;i<n;i++){
            if(A[i] == A[i-1])
                move++;
            else
                A[i-move] = A[i];
        }
        return n - move;
    }

Log in to reply
 

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