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 same array, go heavy, and keep the linear space.
All said the problem is not difficult, but the problem is always done wrong, the beginning of the double cycle, time expired
Later read the answer, with two pointers, a point to be compared with the current element, a point to be compared to the following number, if the following number and this number is equal, then the pointer backward push, straight to find a different number, then move this number, and then continue to compare, the back of the number are moved over.
1 PackageRemove.Duplicates.from.Sorted.Array;2 3 Public classRemoveDuplicatesfromSortedArray1 {4 Public intRemoveDuplicates (int[] A) {5 intlen=a.length;6 if(len<=1)returnLen;7 intFirst=0;8 intSecond=1;9 while(second<Len) {Ten if(a[first]==A[second]) { Onesecond++; A}Else{ -first++; -a[first]=A[second]; thesecond++; - } - - } + returnFirst+1; - } + Public Static voidMain (String args[]) { ARemoveDuplicatesfromSortedArray1 service=NewRemoveDuplicatesfromSortedArray1 (); at int[]a={1,1,1,1,2,3,3}; - intA=service.removeduplicates (A); - - System.out.println (a); - - } in}
Leetcode Remove duplicates from Sorted Array