Remove duplicates from Sorted Array II
Leetcode
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].
Given an ordered table, each element appears up to two times. Remove the extra elements and return the number of remaining elements.
Ideas:
Two pointers, one pointing to the next position in the legal position (index)
, and the other for traversing the element (i)
. The invalid element is between two pointers.
This is the time i
to determine whether the element pointed to is the same as index - 2
the element pointed to.
- Same:
i
the description points to an element that is superfluous and invalid. i
move back.
- Not the same: indicates that
i
the element pointed to is valid, that is, not more than 2 occurrences. At this point, i
replace it index
. index
need to move back
can be viewed in the markdown documentation: Click to open the link code as follows:
class Solution {
public:
int removeDuplicates(int A[], int n) {
int deleted = 0; //已经删除的元素个数
if(n < 3) //最多含有2个元素,一定满足题意
return n;
int index = 2; //可能不合法的位置
for(int i = 2; i < n; i++)
{
if(A[i] != A[index - 2] )
A[index++] = A[i];
}
return index;
}
};
(Daily algorithm) Leetcode---Remove duplicates from Sorted Array II (remove duplicate element II)