Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
Do the allocate extra space for another array, and you must does this on 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].
Test instructions: Remove duplicate elements, if duplicate only one, return length.
Idea: Iterate over the array, with different, overlay the same. Procedure: Saves the subscript lo of the first element. If you encounter equality regardless, continue traversing, encounter unequal, assign the value to the next of Lo, repeat this. The code is as follows:
1 classSolution2 { 3 Public:4 intRemoveDuplicates (intA[],intN)5 {6 if(n<=0)return 0;7 intlo=0;8 for(intI=1; i<=n-1;++i)9 {Ten if(A[lo]! =A[i]) Onea[++lo]=A[i]; A } - returnlo+1; - } the};
The same idea, another way of writing:
1 classSolution {2 Public:3 intRemoveDuplicates (intA[],intN)4 {5 if(n<2)returnN;6 intCount=1;7 intflag=0;8 for(intI=0; i<n;++i)9 {Ten if(A[flag]! =A[i]) One { Aa[++flag]=A[i]; -count++; - } the } - returncount; - } -};
[Leetcode] Remove duplicates from sorted array removes duplicate elements from a sorted array