Clear python solution


  • 0
    Q
    class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        if not A:
            return 0
        p = 1#position of the last unique element
        for i in range(1,len(A)):
            if A[i] != A[i-1]:
                A[p] = A[i]
                p += 1
        return p

  • 0
    L
    This post is deleted!

  • 0
    L

    You should check the title of the problem. It did just ask you about the number of unique elements. The list A need to be changed, too.

    class Solution:
    # @param a list of integers
    # @return an integer
        def removeDuplicates(self, A):
            if not A:
                return 0
            p = 1#position of the last unique element
            for i in range(1,len(A)):
                if A[i] != A[i-1]:
                    A[p] = A[i]
                    p += 1
            A = A[:p]
            return p

  • 0
    G

    This doesn't make sense because you do A = A[:p] but this won't affect the A outside.


  • 0
    L

    Yes, you are right.Thanks to point it out. There is no way we can make the actual list in the outer scope shorter. The reason is that list in parameter, as a mutable type, we CAN mutate it as we want but just not able to make it shorter with del(),remove() and pop(). The parameter A is a copy of a reference of A in outer scope, A= A[:p] will make that copy of reference point to a new list, but there is no way to change where outer A pointed.http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference


Log in to reply
 

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