问题描述
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.
解决思路
很简单的ac了这一道题,但是因为其还要对数组进行改变,我生成了一个临时变量去存储新数组,然后再赋值给旧数组。但是看了别人的解答后觉得这种方法真的好蠢。直接贴大神的代码吧。看了也秒懂。代码
int removeDuplicates(vector<int>& nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}