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
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?
I don't understand why this code works with an input like A=[1,1,1]. It didn't change A to , but this is required, right?
In your code you counted all different numbers. However you forget to delete the duplicate elements in A.
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.
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.
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.
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!
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.