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]
.
The problem is to remove duplicates from the ordered array, which is similar to the previous remove duplicates from Sorted list to remove duplicates in the ordered list, but simply because the values of the array can be accessed directly through the subscript, but not the list. So the problem of the idea is that we use a fast pointer to record the traverse of the coordinates, at the beginning of the two pointers point to the first number, if the two pointer refers to the same number, then the quick pointer forward one step, if different, then two pointers forward one step, so that when the fast pointer through the entire array, The current coordinates of the slow pointer plus 1 are the number of different arrays in the array, the code is as follows:
classSolution { Public: intRemoveDuplicates (intA[],intN) {if(N <=1)returnN; intPre =0, cur =0; while(Cur <N) {if(A[cur] = = A[pre]) + +cur; ElseA[++pre] = a[cur++]; } returnPre +1; }};
[Leetcode] Remove duplicates from Sorted array to remove duplicates in ordered arrays