My accepted python code via while loop


  • 6
    L
    class Solution:
    # @param a list of integers
    # @return an integer
    
    def removeDuplicates(self, A):
        if not A:
            return 0
        else:
            ii,jj=1,1
            while jj<len(A):
                if A[ii-1]!=A[jj]:
                    A[ii]=A[jj]
                    ii+=1
                jj+=1
            return ii
    

    the code use a while loop with two indexes ii and jj. jj went through all elements in A and ii is used to record non-duplicated elements in A. Any comments would be appreciated


  • 0
    C
    class Solution:
        # @param a list of integers
        # @return an integer
        def removeDuplicates(self, A):
    		if A == []:
    			return(0)
    		count = 1;
    		for i in range(1,len(A)):
    			if A[i] != A[i-1]:
    				count += 1
    		return(count)
    

    can you help me to check why my solution is wrong?


  • 0
    H

    I don't understand why this code works with an input like A=[1,1,1]. It didn't change A to [1], but this is required, right?


  • 0
    L

    Hi chanvee,
    In your code you counted all different numbers. However you forget to delete the duplicate elements in A.


  • 0
    L

    For your specific case A=[1,1,1], the code does not change matrix A at all. However the return value is 1 which determines the length of unduplicated parts in A.


  • 0
    D

    I think the point is that the grader doesn't care about changing the whole A, but only the first n items (where n is the resulting length). So it returns something like A[:n]. Which is in fact rather effective: you don't bother changing the size of the array which is computationally expensive.


  • 0
    M

    Thanks for sharing your solution! The question should probably be modified if only the first n items in the array are examined, since it specifies that they should be removed, and for Python at least lists don't work like C arrays where the length is only stipulative.


  • 1
    S

    Thanks for your sharing! I tried your solution. input: nums = [1, 1, 1, 2, 1, 1, 2], output: 4, [1, 2, 1, 2, 1, 1, 2]. It should be 2 instead of 4, yes?
    I am not good at two pointers problem. Thanks!


  • 0
    L

    Hi Sen5, It seems for this problem, the given array is sorted. For your test case, this algorithm is not appropriate. Let me know if you have any additional questions.


Log in to reply
 

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