LeetCode 80 Remove Duplicates from Sorted Array II
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, with the first five elements of nums being 1, 1, 2, 2 and 3.
It doesn't matter what you leave beyond the new length.
DiffcultyMedium
Similar Problems
[LeetCode 26] Remove Duplicates
Analysis
Similar to the problem Remove Duplicates
, the only difference is that when A[end-1] == A[end] == A[i], A[i] is the duplicate number and we should skip it.
So we actually only need to compare A[end-1] and A[i], since when A[end-1] == A[i], there must be A[end] = A[end-1] since it is a sorted array.
A = [1, 1, 1, 2, 2, 3]
^ ^
end
Solutions
1. Cpp solution
class Solution {
public:
int removeDuplicates(vector<int>& A) {
const int n = A.size();
if(n < 3) return n;
int end = 2;
for(int i = 2; i < n; i++) {
if(A[i] != A[end - 2])
A[end++] = A[i];
}
return end;
}
};
2. Go solution
func removeDuplicates(nums []int) int {
n := len(nums)
if n < 3 {
return n
}
end := 2
for i := 2; i < n; i++ {
if nums[end-2] != nums[i] {
nums[end] = nums[i]
end++
}
}
return end
}