Remove duplicates from Sorted array: Removes duplicate elements from the array that is arranged
To investigate the basic operation of an array:
classSolution { Public intRemoveDuplicates (int[] nums) { if(nums==NULL|| Nums.length==0) return0; intindex = 1; for(inti = 1; i<nums.length; i++){ if(nums[i]!=nums[i-1]) {Nums[index]=Nums[i]; Index++; } } returnindex; } Public Static voidMain (string[] args) {int[] arr = {1, 2, 2, 3, 3 }; Arr=removeduplicates (arr); System.out.println (Arr.length);}}
Remove duplicates from Sorted Array II (Java)
For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A are now [1,1,2,2,3].
Allows up to two duplicates, resulting in an array of output results.
Solution 1: When the counter is 2 o'clock, you can skip directly, otherwise the number of occurrences of the element is not super, continue to put into the result array, if new elements encountered reset counter. The overall algorithm only needs to scan the array once, so the time is O (n), the space only need to maintain an index and counter, so is O (1).
Public intRemoveDuplicates (int[] A) {if(a==NULL|| A.length==0) return0; intIDX = 0; intCount = 0; for(inti=1;i<a.length;i++) { if(a[i]==a[i-1]) {count++; if(count>=3) Continue; } Else{Count= 1; } a[idx++]=A[i]; } returnidx;}
Solution Two:
Public classSolution { Public intRemoveDuplicates (int[] A) {if(A.length <= 2) returna.length; intprev = 1;//Point to previous intCurr = 2;// Point-to-current while(Curr <a.length) {if(A[curr] = = A[prev] && A[curr] = = A[prev-1]) {Curr++; } Else{prev++; A[prev]=A[curr]; Curr++; } } returnPrev + 1; }}
leetcode-array: Remove duplicates from Sorted array