题目:
Given a sorted array, remove the duplicates in place such that > each element appear only once
and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].是在一个排序好的数组里面删除重复的元素
思路:
譬如一个数组为1,1,2,3,首先i = 1,j = 0,这时候A[i] = A[j],于是递增i,碰到2,不等于1,此时设置A[j + 1] = A[i],也就是A[1] = A[2],递增i和j为3和1,这时候A[3] != A[1],设置A[j + 1] = A[i],也就是A[2] =A[3],再次递增,遍历结束。这时候新的数组长度就为2 + 1,也就是3。
代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int a, n = 0,j=0;
vector<int> v;
while(cin>>a)
{
v.push_back(a);
n++;
}
if(n==0)
return 0;
for(int i=1;i<n;i++){
if(v[j]!=v[i]){
v[++j]=v[i];
}
}
cout<<j+1<<endl;
return 0;
}
运行结果:
如果同样是移除重复的元素,但是可以允许最多两次重复元素存在。这时我们需要用一个计数器来记录重复的次数,如果重复次数大于等于2,我们会按
照第一题的方式处理,如果不是重复元素了,我们将计数器清零。
代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int a, n = 0,j=0,num=0;
vector<int> v;
while(cin>>a)
{
v.push_back(a);
n++;
}
if(n==0)
return 0;
for(int i=1;i<n;i++){
if(v[j]==v[i])
{
num++;
if(num<2)
{
v[++j]=v[i];
}
}else{
v[++j]=v[i];
num=0;
}
}
cout<<j+1<<endl;
return 0;
}
运行结果: