查找数组中出现次数超过一半的数

查找数组中出现次数超过一半的数

解法一 对数组运用快排,取 n/2处的数为超过一半的数

解法二 用空间换时间,以散列表中存储出现过的数据,和出现的次数

解法三 每次 删除数组中两个不同的数,剩下的那个数就是出现次数超过一半的数

解法四 保存两个值 ,candidate用来保存数组中遍历的某个数,nTimes 用来保存遍历到的数出现的次数

int findOneNumber(int *a,int n)
{
	int candidate, nTimes;
	candidate = 0;
	nTimes = 1;
	for (int i = 1; i < n; i++)
	{
		if (nTimes == 0)
		{
			candidate = i;
			nTimes = 1;
		}
		else
		{
			if (a[candidate] == a[i])
			{
				nTimes++;
			}
			else
			{
				nTimes--;
			}
		}
	}
	return candidate;
}
int main()
{
	int a[] = { 0,1,2,1,1 };
	int index = findOneNumber(a, 5);
	cout<<a[index];
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值