My one-pass solution


  • 5
    H
    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            if (n == 0)
            {
                return n;
            }
            int k = 0;
            for (int i = 1; i < n; i++)
            {
                if (A[i] != A[k])
                {
                    A[++k] = A[i];
                }
            }
            return k + 1;
        }
    };

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    J

    This block of code
    int tmp = A[i]; A[i] = A[k]; A[k] = tmp; last = A[k];
    could be
    A[k] = A[i]; last = A[i];


  • 2
    G

    The code can be more compact. See the following solution

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

  • 0
    X

    The method is:

    • Check if the length is 0, if it is, then return 0.

    • Initialize the a counter, say k to be 0.

    • Go from 1 in a for loop:
      (Note that k should be 1 less than i for comparison)

      • if element at k is different from at i, then update k by 1, and set element at k+1 be A[i]
      • do nothing else
    • As our counter is at first 1 less than the really length, we return counter + 1.


Log in to reply
 

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