LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素II)

时间:2023-03-09 07:13:38
LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素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 1122 and 3. It doesn't matter what you leave beyond the new length.

典型的双指针问题,维护两个指针不断更新就可以了,代码如下:

 class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int sz = nums.size();
if(!sz) return ;
int start = ;//第二个指针
int i = ;//第一个指针
int count = ;
int key = nums[];
for(; i < sz; ++i){
if(nums[i] == key)
count++;
else{
for(int k = ; k < min(, count); ++k)
nums[start++] = key;//更改数组元素,指针前移
key = nums[i];
count = ;
}
}
for(int k = ; k < min(, count); ++k)
nums[start++] = key;
return start;
}
};