leetcode:数组:Remove Duplicates from Sorted Array

leetcode:数组之Remove Duplicates from Sorted Array

去除有序数组中重复的元素,例如a=[1,1,2,3];输出a=[1,2,3],返回数组长度。

主要思路:取出每一个元素,通过if判断直到遇到不相同的元素,写入数组中

c++实现

#include<iostream>

using namespace std;

int removeDuplicate(int a[],int n)
{
	if(n==0) return n;

	int index=0;
	for(int i=1;i<n;i++)
	{
		if (a[index] != a[i])
		{
			++index;
			a[index] = a[i];
			 
		}

	}
	return index+1;
}

int main()
{
	int a[4]={1,1,2,3};
	int lenght;
	lenght=removeDuplicate(a,4);
	for(int i=0;i<lenght;i++)
		cout<<a[i];
	cout<<endl<<lenght<<endl;

	return 0;
}


测试结果:


leetcode:数组之Remove Duplicates from Sorted Array 2

去除有序数组中重复次数为3的元素,例如a=[1,1,1,2,2,3];输出a=[1,1,2,2,3],返回数组长度。

C++实现:

#include<iostream>

using namespace std;

int removeDuplicate2(int a[],int n)
{
	if(n<=2) return n;

	int index=2;
	for(int i=2;i<n;i++)
	{
		if( a[index-2]!=a[i])
		{
			a[index++]=a[i];
		}
	}
	return index;
}

int main()
{
	int a[6]={1,1,1,2,2,3 };
	int lenght=0;
	lenght=removeDuplicate2(a, 6);
	for(int i=0;i<lenght;i++)
		cout<<a[i];
	cout<<endl<<lenght<<endl;

	return 0;
}

 
测试结果: 



根据Remove Duplicates from Sorted Array 2,可扩展为去除重复次数为n的数组。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值