Remove Duplicates from Sorted Array II
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?For example,
Given sorted array nums = [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.
Like what we have learned in Remove Duplicates from Sorted Array, now
I write down universal code for allowing duplicates once, twice or more
after removement.
NOW ATTENTION PLEASE:
Given a sorted
array numbers, how can we remove duplicate elements in this array, what if duplicates are allowed at most once, twice or more
?
Note that, if the array is not sorted
, just one variable is not enough; hashmap
will be needed to record the times.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 2) return nums.size();
int index = 2;
for(int i = 2; i < nums.size(); ++i){
if(nums[i] != nums[index -2]){
nums[index++] = nums[i];
}
}
return index;
}
};
Conclusion
1.Sorted array
2.Remove duplicate elements
3.the at most times of duplicate elements