Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
Solution
多一个变量记录当前元素出现的次数。
class Solution {
public:
/**
* @param A: a list of integers
* @return : return an integer
*/
int removeDuplicates(vector<int> &nums) {
if(nums.empty()) return 0;
int len = 1;
int pivot = nums[0];
int counter = 1;
for(int i=1; i<nums.size(); i++) {
if(nums[i] == pivot) {//duplicated, then check counter
if(counter ==1) {
counter++;
nums[len++] = nums[i];
}
} else {//update pivot
counter = 1;
nums[len++] = nums[i];
pivot = nums[i];
}
}
return len;
}
};