Issue: Remove duplicates from Sorted Array II Difficulty: Medium
Follow up for "Remove duplicates":
What if duplicates is allowed at the most twice?
For example,
Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3].
Answer:
Two ways of thinking:
(1) Two reference pointers, step back, and when the 3rd is equal to the first 2, skip
(2) A reference pointer, which is compared with 3rd and 1th, when equal, skips; unequal assignment
It is obvious that (1) is easy to think (intuitive), but (2) is more efficient and more scalable (if the requirements are up to 3 times, only the comparison of A[i] and a[index-3]).
Therefore, in the conception should pay attention to the conversion to the equivalence problem, when ordered, compare and the first n is equal, only need to compare the current and the first (i-n) equality.
class solution { Public://Compare 1 times, assign value 1 times intRemoveDuplicates (intA[],intN) {if(N <=2)returnNint Index=2; for(inti =2; I < n; i++) {if(A[i] = = a[Index-2])Continue; a[Index+ +] = A[i]; }return Index; }//Compare 2 times, assign value 2 times intRemoveDuplicates2 (intA[],intN) {if(N <=2)returnNintj =0;intK = j+1; A[J] = a[0]; A[k] = a[1]; for(inti =2; I < n; i++) {if(A[i] = = A[k] && a[j] = = A[k])Continue; A[++J] = a[k]; A[++K] = A[i]; }returnK +1; } };};
Leetcode 4. Remove duplicate elements from an ordered array remove duplicates from Sorted array