题目:
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;
}
};
本文介绍了一种改进的去重算法,该算法允许数组中的元素最多重复两次,并返回处理后的有效长度。通过Two Pointers的方法,在遍历过程中判断当前元素是否与前两个元素相同来决定是否加入结果中。

被折叠的 条评论
为什么被折叠?



