Follow up for "remove duplicates ":
What if duplicates are allowed at mostTwice?
For example,
Given sorted array A =[1,1,1,2,2,3],
Your function shocould return length =5, And a is now[1,1,2,2,3].
Question:
Set two variables: Kepler on the right and forward cursor forward. If the element referred to by the current kepeler is equal to its next element, store the two equal elements to A, then set forward to kepeler + 2, move forward, if all elements are equal to the elements referred to by the current kepeler, ignore them. Otherwise, move the kepeler to the elements referred to by the forward and continue the loop; if the element referred to by the current kepeler is not the same as the next element, the element is directly added to a, and the kepeler moves forward and continues the loop.
For example, the array given in the question is.
When the initial kepeler points to the first 1 and finds that kepeler + 1 is also a 1, the forward is set to kepeler + 2 = 2 for forward detection. When the element whose index is 3 is detected, if it finds that the element is not the same as that referred to by kepeler, move kepeler to 3 and continue the above process to get the array, 3.
The Code is as follows:
1 public class solution {2 Public int removeduplicates (INT [] A) {3 if (a = NULL |. length = 0) 4 return 0; 5 Int kepeler = 0, forward = 0; 6 int newsize = 0; 7 8 while (kepeler <. length) {9 If (kepeler + 1 <. length & A [kepeler + 1] = A [kepeler]) {10 A [newsize ++] = A [kepeler]; // two identical elements exist, all are in the array. 11 A [newsize ++] = A [kepeler]; 12 forward = kepeler + 2; 13 while (Forward <. length & A [forward] = A [kepeler]) 14 forward ++; 15 kepeler = forward; 16} 17 else if (kepeler <. length) {18 A [newsize ++] = A [kepeler]; 19 kepeler ++; 20} 21} 22 return newsize; 23} 24}