Topic:
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]
.
Ideas:
You can draw on the two pointer movement method of the remove duplicates from Sorted array.
However, some details need to be considered. For example, we need to continue to assign values that are less than 3 repetitions to the past, and more than 3 to move only the point pointer, searching forward for unequal numbers. We just skipped the third one, because it's an ordered array, so we can compare directly with the first two of the previously obtained array (an array maintained by L-en ), i.e. if a[point] = = A[len-2], then a[point]==a[len-2] ==a[len-1]. This array maintains a repeating number of up to two arrays. When not repeating, we just constantly assign values that are not duplicated (or less than 2) to the array maintained by Len. Move the Len and point pointers at the same time. When you repeat more than 2, we only move the point, searching forward for unequal numbers.
Attention:
1. Take note of the initial Len and point values.
int len = 2, itor = 2;
2. Note that we do not need to count fewer than 3 arrays.
Complexity: O (N)
AC Code:
Class Solution {public: int removeduplicates (int a[], int n) { if (n <= 2) return n; int len = 2, point = 2; while (Point < N) { //if a[point]! = a[len-2], because it is an ordered array, represents a[point]! = a[len-1] && a[point]! = A[len], i.e. A [Point] is not a third repeating number //If it is then continue to move point until the unequal number is found, the assigned A[len],len will stay at the position of the third repeating number (if there are more than 3 repetitions), and no more than 3 //duplicate numbers will be assigned. Len also moves along. if (a[point]! = a[len-2]) a[len++] = A[point]; point++; } return len; };
[C + +] leetcode:72 Remove duplicates from Sorted Array II