题目描述:
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 class Solution { 2 public: 3 int removeDuplicates(vector<int>& nums) { 4 if(nums.size() <= 2) 5 return nums.size(); 6 int DupNum = 1; 7 for(int i = 1; i < nums.size(); i++){ 8 if(nums[i] != nums[i-1]) 9 DupNum = 1; 10 else{ 11 DupNum++; 12 if(DupNum > 2) 13 nums.erase(nums.begin()+(i--)); 14 } 15 } 16 return nums.size(); 17 } 18 };