LeetCode 80. Remove Duplicates from Sorted Array II
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.
此题目是在这个题目Remove Duplicates from Sorted Array做的升级。
现在要求对于已经排序的数组,最多要求两次重复出现。
解析:
思路与前一个题目类似,采用两个指针,i用于遍历整个数组,index表示没有重复元素的新数组的尾部。当nums[index]与nums[index-2],nums[index-1]相等时说明连续三个元素相等,此时需要把nums[i]的元素复制到nums[index]的位置。
[cc lang=”C++”]
class Solution {
public:
int removeDuplicates(vector
if (nums.size() <= 2) return nums.size();
int index = 2;
for(int i=2; i
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
[/cc]
因为原始数组已经排好序,所以当不存在重复元素的时候 n > nums[i-2]。