一. 题目:Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3]
, your function should return length = 5
, and A is now [1,1,2,2,3]
二. 思路分析
因为题目是所给数组已经排序的数组,所以加一个变量记录一下元素出现的次数,这样加一个变量即可解决。代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() <= 2) return nums.size();
int index = 2;
for (int i = 2; i < nums.size(); i++){
if (nums[i] != nums[index - 2])
nums[index++] = nums[i];
}
return index;
}
};