#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
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.
分析:这次是如果有重复的元素,至少保留两个重复的元素。
可以遍历到每个元素的时候,设定一个计数器,当计数器为3的时候,就记录此时位置为待删除位置。
一遍扫描后,得到所有删除的位置,在从后向前遍历,删除待删除位置的上元素
输入:
6(数组元素个数)
1 1 1 2 2 3
输出:
5
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
{
return 0;
}
int size = nums.size();
vector<int> deleteFlags(size , 0);//0表示不删除
int count = 1;
int value = nums.at(0);
for(int i = 1 ; i < size ; i++)
{
//找到重复的元素,累加计数器
if(nums.at(i) == value)
{
count++;
//找到待删除位置
if(count > 2)
{
deleteFlags.at(i) = 1;
}
}
//非重复元素,重新设定计数器和元素
else
{
value = nums.at(i);
count = 1;
}
}
//从后向前删除指定位置上的元素
for(int i = size - 1 ; i >= 0 ; i--)
{
if(1 == deleteFlags.at(i))
{
nums.erase(nums.begin() + i , nums.begin() + i + 1);
}
}
if(nums.empty())
{
return 0;
}
int result = nums.size();
return result;
}
};
void print(vector<int>& result)
{
if(result.empty())
{
cout << "no result" << endl;
return;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
cout << result.at(i) << " " ;
}
cout << endl;
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
while(cin >> num )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
int result = solution.removeDuplicates(nums);
cout << result << endl;
//print(nums);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:80. Remove Duplicates from Sorted Array II
最新推荐文章于 2024-01-02 23:35:28 发布
