Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
解题思路:
与上一道题目思路一模一样,见:【简单】Lintcode 100: Remove Duplicates from Sorted Array,区别只是将两指针之间的距离从1变成了2即可。
class Solution { public: /** * @param A: a list of integers * @return : return an integer */ int removeDuplicates(vector<int> &nums) { // write your code here if(nums.size() < 3) return nums.size(); vector<int>::iterator cur = nums.begin(); vector<int>::iterator afr = nums.begin() + 2; while(afr != nums.end()) { if(*cur == *afr) nums.erase(afr); else { cur++; afr++; } } return nums.size(); } };