Wednesday, April 16, 2014

LeetCode: 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].


Set up two indices, one for iterating the array, one for keep count of the non-duplicates.

C++ Code:

/*
 * func: remove_duplicates_from_sorted_array
 * goal: given a sorted array, remove the duplicate in place
 * @param A: input array
 * @param n: the length of the array
 * return: the length of the array without duplicates
 */
int remove_duplicates_from_sorted_array(int A[], int n){
    //If the length is less than 1, there is no need to remove
    if(n <= 1){
        return n;
    }
    int current = A[0];
    int i = 1;
    int new_i = 1;
    while(i<n){
        //If the next one is equal to the current one, move to the next
        if(A[i] == current){
            ++i;
        }else{
            //Store the next different element, and move two index forward
            A[new_i] = A[i];
            current = A[new_i];
            ++new_i;
            ++i;
        }
    }
    
    return new_i;
}

Python Code:

# func: remove duplicates from sorted array
# @param A: the list of array
# @return: the length of new array
def remove_duplicates_from_sorted_array(A):
    if len(A) <= 1:
        return len(A)
    else:
        j = 0
        for i in xrange(1, len(A)):
            if A[i] == A[j]:
                continue
            else:
                j += 1
                A[j] = A[i]
        return j+1

No comments:

Post a Comment