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.
需要注意到:数组是已经排好序的,以及元素最多可以有两个重复。我们可以用两个指针,一个i遍历所有元素,一个index指向新元素或者第3(4,5...)个重复的元素,每次i指向的元素都赋给index指向的元素。最后index的值就是新数组的长度,代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int index=0;
int length=nums.size();
for(int i=0;i<length;i++){
if(index<2||nums[i]>nums[index-2])
nums[index++]=nums[i];
}
return index;
}
};

本文介绍了一种在已排序数组中去除多余重复项的算法,该算法允许每个元素最多出现两次,并返回更新后的数组长度。通过使用双指针技术,此方法能有效地处理数组中的重复元素。
488

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



