Remove Duplicates from Sorted Array

题目:

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;
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值