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 int len=nums.size(); 5 if(len<1) 6 return 0; 7 int end=0,flag=0; 8 for(int i=1;i<len;i++) 9 { 10 if(nums[i]==nums[end]) 11 { 12 if(flag==1) 13 { 14 15 continue; 16 } 17 flag=1; 18 } 19 else 20 flag=0; 21 end++; 22 if(i!=end) 23 nums[end]=nums[i]; 24 } 25 return end+1; 26 } 27 28 };