您的位置:首页 > 其它

LeetCode 80. Remove Duplicates from Sorted Array II

2016-07-06 14:41 369 查看

描述

给出一个数列,求出一个数列,使得其中重复元素的次数最多不超过2次,问这个数列的长度,并要求把该长度下的数存放在数列中。

解决

利用一个标志cnt,统计当前数在结果数列中出现的次数,遍历过去即可。O(n)

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int lenth = nums.size();
if (lenth == 0){
return 0;
}
int index = 0;
nums[index] = nums[0];
int cnt = 1;
for (int i = 1; i < lenth; ++i){
if((nums[i] == nums[index] && cnt == 1)){
nums[++index] = nums[i];
++cnt;
}
else if (nums[i] != nums[index]){
nums[++index] = nums[i];
cnt = 1;
}
}
return index + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode