Sunday, June 15, 2014

LeetCode (Python): Remove Duplicates from Sorted Array

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 = [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

3 comments :

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. You could use a dictionary to keep track of this - simple and easy.

    ReplyDelete