您的位置:首页 > 其它

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

2015-10-29 22:58 495 查看
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.

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

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int sz = nums.size();
if(!sz) return 0;
int start = 0;//第二个指针
int i = 0;//第一个指针
int count = 0;
int key = nums[0];
for(; i < sz; ++i){
if(nums[i] == key)
count++;
else{
for(int k = 0; k < min(2, count); ++k)
nums[start++] = key;//更改数组元素,指针前移
key = nums[i];
count = 1;
}
}
for(int k = 0; k < min(2, count); ++k)
nums[start++] = key;
return start;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: