题目
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.
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
解答
这个解答太精秒了!!
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int i=0;
for(int j=0;j<nums.size();j++)
{
if(i<2||nums[j]>nums[i-2])
{
nums[i]=nums[j];
i++;
}
}
return i;
}
};
参考:https://discuss.leetcode.com/topic/17180/3-6-easy-lines-c-java-python-ruby
Just want to confirm, this solution can be easily generalized to "at most K duplicates", right?
int removeDuplicates(vector<int>& nums, int k) {
int i = 0;
for (int n : nums)
if (i < k || n > nums[i-k])
nums[i++] = n;
return i;
}