title :
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]
.
Code :
classSolution { Public: intRemoveDuplicates (intA[],intN) {if(N <=2)returnN; intindex =2; for(intI=2; i<n; i++) { if(a[index-2]!=A[i]) {A[index++] =A[i]; } } returnindex; }};
Tips:
1. Index always points to the next location to insert the element
2. Determine whether the current element and index-2 position elements are equal, if not equal, can be inserted to ensure that there are no consecutive three identical elements
3. Here are some techniques for mathematical induction:
A. As long as the 1th-3rd element is not all the same
B. And when you add elements to each step, the judgment is not the same.
You can get the conclusion until the end of the condition, there will be no three consecutive repeating elements in the adjusted array
"Remove duplicates from Sorted Array II" cpp