Remove duplicate numbers ii remove-duplicates-from-sorted-array-ii
Title description
Continue to think about the topic "Remove Duplicates":
Given a sorted array, remove duplicate elements.
What if the elements in the array are allowed to be repeated twice?
For example:
Given an ordered array A =[1,1,1,2,2,3],
the function you give should return length =5, and A becomes [1,1,2,2,3].
Follow up for “Remove Duplicates”:
What if duplicates are allowed at 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].
Problem-solving ideas
- Use fast and slow two pointers to record the non-duplicated area and traverse the array
- The pointer cnt is used to record the right subscript of the non-repeated area. The initial value is 0, which means there is one element.
- The pointer index is used to traverse the elements, the initial value is 1, and the traversal starts from the second element.
- maxnum is used to indicate the number of repetitions of the element, the initial value is 1, which means that the element only appears once
- If A[cnt] == A[index], then maxnum++, further judgment:
- If maxnum<=2, then A[++cnt] = A[index],index++
- If maxnum>2, skip, index++
- If A[cnt]! = A[index], then A[++cnt] = A[index],index++, and because the elements are different, maxnum must be initialized to 1, which means that the number of repetitions of the next element is re-recorded
- If A[cnt] == A[index], then maxnum++, further judgment:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n <= 1) return n;
int cnt(0), maxnum(1);
for(int index = 1; index < n; index ++) {
if(A[cnt] == A[index]) {
maxnum ++;
if(maxnum <= 2) {
A[++ cnt] = A[index];
}
} else {
//A[cnt] != A[index]
maxnum = 1;
A[++ cnt] = A[index];
}
}
return cnt + 1;
}
};