(Daily algorithm) LeetCode --- Remove Duplicates from Sorted Array II (delete duplicate element II)
Remove Duplicates from Sorted Array II
Leetcode
Question:
Follow up for "Remove Duplicates ":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1, 1, 2, 2, 3],
Your function shocould return length = 5, and A is now [, 3].
Given an ordered table, each element can appear at most twice. Delete unnecessary elements and return the number of remaining elements.
Ideas:
Two pointers, one pointing to the next location in a valid position(index)
And the other is used to traverse elements.(i)
. The two pointers are invalid elements.
Judge at this timei
Elements andindex - 2
Whether the elements to be pointed to are the same.
Same: Description
i
The pointing element is redundant and invalid.
i
Move back. Different: Description
i
The pointing element is valid, that is, the number of occurrences is no more than two times. In this case, use
i
Replace
index
You can.
index
If you need to move it back, you can view it in the Markdown document: Click to open the link. The Code is as follows:
class Solution {
public:
int removeDuplicates(int A[], int n) {
Int deleted = 0; // Number of deleted elements
If (n <3) // contains a maximum of 2 elements.
return n;
Int index = 2; // The location may be invalid.
for(int i = 2; i < n; i++)
{
if(A[i] != A[index - 2] )
A[index++] = A[i];
}
return index;
}
};