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 ;
}
---------------------------------------------------------------------------------
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
Post a Comment