题目:
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.
思路:
还是Two Pointers的思路,和Remove Duplicate的解法基本一致,只是我们在扫描的过程中,需要判断扫描到的数字与当前结果的最后两个数字是否相同,只有当三者都相同的时候才不需要将当前数字添加到结果中。下面代码的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() <= 2)
return nums.size();
int last = 1;
for(int i = 2; i < nums.size(); ++i)
{
if(nums[i] != nums[last] || nums[i] != nums[last - 1])
swap(nums[i], nums[++last]);
}
return last + 1;
}
};