标签:
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.
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=2) return nums.size(); vector<int> num_new; int len=1; int n=1; int begin=nums[0]; num_new.push_back(nums[0]); for(int i=1;i<nums.size();i++) { if(nums[i]==begin) { if(n<2) { len++; num_new.push_back(nums[i]); } n++; } else { begin=nums[i]; len++; num_new.push_back(nums[i]); n=1; } } nums=num_new; return len; } };
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=2) return nums.size(); int len=0; int n=0; int begin=nums[0]; for(int i=1;i<nums.size();) { if(*(nums.begin()+i)==begin) { n++; if(n>1) { nums.erase(nums.begin()+i); } else i++; } else { begin=*(nums.begin()+i); i++; n=0; } } return nums.size(); } };
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size()<=2) return nums.size(); int rear=1; for(int i=2;i<nums.size();i++) { if(!(nums[i]==nums[rear]&&nums[i]==nums[rear-1])) nums[++rear]=nums[i]; } return rear+1; } };
Remove Duplicates from Sorted Array II
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46627937