Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =
Given input array A =
[1,1,2]
,
Your function should return length =
2
, and A is now [1,2]
.Solution:
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if len(A)==0: return 0 end = 0; for i in range(1,len(A)): if A[i] != A[end]: end += 1 self.swap(A,i,end) return end + 1 def swap(self, A, pos1, pos2): temp = A[pos1] A[pos1] = A[pos2] A[pos2] = temp
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteYou could use a dictionary to keep track of this - simple and easy.
ReplyDelete