O(n) solution with Python


  • 0
    S
    class Solution:
    # @param A a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        if A is None:
            return 0
        length = len(A)
        result = 0
        i = j = 0
        while i < length:
            j = i 
            while j < length:
                if A[j] != A[i]:
                    break
                j += 1
            if j-i > 2:
                length -= j-i-2
                for k in range(j-i-2):
                    del A[i]
                result += 2
                j = i+2
            else:
                result += (j-i)
            i = j
        return result

Log in to reply
 

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