Question:
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.
允许重复2次,删除重复超过3次的元素,返回删除后的长度。
Algorithm:
见程序
Accepted Code:
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=2)return nums.size(); vector<int>::iterator it=nums.begin(); for(;it!=nums.end();) { int temp=*it; int j=0; while(*it==temp) { if(it==nums.end()) break; j++; if(j>2) nums.erase(it); else it++; } } return nums.size(); } };
时间: 2025-01-16 03:32:30