您的位置:首页 > 其它

80. Remove Duplicates from Sorted Array II

2016-06-09 21:42 218 查看
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.

Analysis:

II和I没有太大区别,加个计数变量即可。

Source Code(C++):

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
if (nums.size() == 1){
return 1;
}
int index=0;
int count=1;
for (int i=1; i<nums.size(); i++){
if (nums.at(i)!=nums.at(index)){
index++;
nums.at(index)=nums.at(i);
count=1;
}
else if (nums.at(i)==nums.at(index) && count<2)
{
count++;
index++;
nums.at(index)=nums.at(i);
}
}
return index+1;
}
};

int main() {
vector<int> v;
v.push_back(1);v.push_back(1);v.push_back(1);v.push_back(2);v.push_back(2);v.push_back(3);
Solution sol;
cout << sol.removeDuplicates(v) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: