Remove Duplicates from Sorted Array

PROBLEM :

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

int removeDuplicates(int* nums, long numsSize) {
    long i;
    if(numsSize==1)
        return numsSize ;

    for(i=0;i<numsSize-1;i++)
    {
        if(nums[i]==nums[i+1])
        {
            Remove(nums,&numsSize,i) ;
            i-- ;
        }
        else
            continue ;
    }
    return numsSize ;
}

void Remove(int *nums,long *numsSize,int i)
{
    long k ;
    for(k=i;k<(*numsSize);k++)
    {
        nums[k]=nums[k+1] ;
    }
 
    (*numsSize)-- ;
}

----------------BETTER SOLUTION------------------------------------------------------------

int removeDuplicates(int* nums, int numsSize) {
    int i,j ;
    if(numsSize==0)
        return 0 ;
    if(numsSize==1)
        return 1 ;
     
    j=0 ;
    for(i=1;i<numsSize;i++)
    {
        if(nums[i]!=nums[j])
        {
             nums[++j]=nums[i] ;
        }
    }
 
    return j+1 ;
}


---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )