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.
此题的目的在于将已经排好序的数组,删除重复的元素,重复元素最多保留两个。
思路:
1.考虑边界值,当数组元素小于2时,则直接返回数组长度;
2.否则,初始化新数组长度length = 2,然后判断nums[length-2]是否等于nums[i];
3.若不相等,则把nums[i]替换掉nums[length],length++;
4.若相等,则不做任何处理;
5.返回length,即为最后的结果,且原数组的前length个元素,即为新数组的元素。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<2) return nums.size();
int length = 2;
for(int i=2;i<nums.size();i++){
if(nums[length -2] != nums[i]){
nums[length] = nums[i];
length++;
}
}
return length;
}
};