题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
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.
思路:因为有些元素需要删除掉,可以将后面的元素往前移动,并且需要一个索引来标记当前可以赋值的位置.每遇到一个新元素就开始计数,如果其个数小于3的地方就赋值并且移动索引位置,否则就不管.
代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() ==0) return 0;
int ans = 1, old = nums[0], cnt = 1, i= 0;
while(++i < nums.size())
{
if(nums[i] != old) nums[ans++]=nums[i], cnt=1, old=nums[i];
else if(++cnt < 3) nums[ans++]=nums[i];
}
return ans;
}
};