How can I remove duplicate elements if remove, del and pop are not allowed?


  • 0
    W

    According to the question description, A = [1,1,2] should be A = [1,2] but if remove, delete, pop are not allowed, how can A be [1,2]?
    I see others' solutions and I think their answer should be like A = [1,2,2] so A is not equal to [1,2] and A still contains duplicate element, is that ok?
    I am quite confused about what the problem asks me to do? A should remain sorted after removing duplicate elements, right?


  • 0
    W

    Yeah, the duplicate elements exactly are not been deleted, just be covered by the following elements.
    For example, A=[1,2,2],after the algorithm, the A still equal to [1,2,2],but your function will return the array length to be 2, not 3. And the judge will print the A with length of 2, so it's ok that the A is still [1,2,2]


  • 0
    X

    Here's my AC python code.

    class Solution:
        # @param a list of integers
        # @return an integer
        def removeDuplicates(self, A):
            if not A:
                return 0
            
            pre, cur = 0, 0
            while cur<len(A):
                if A[pre]==A[cur]:
                    cur+=1
                else:
                    A[pre+1]=A[cur]
                    pre+=1
    
            for i in range(len(A)-1,pre,-1):
                A[i]=[]
            return pre+1
    

    As you can see, you can use A[i]=[] to delete the i+1th element in array A.


  • 0
    C

    This solution has multiple problems:

    1. It creates new lists, specifically the placeholders elements in your list. This is specifically forbidden in the problem.

    2. The list returned is not what is asked for in the problem. It asks for an array with the duplicate elements removed. What is returned in this solution are the list with duplicate elements removed, and some empty lists inserted.

    I do not understand how this could be an accepted answer, except for the fact that it does not seem to be possible to do the problem correctly in Python without using del() or remove().


Log in to reply
 

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