王道ch1-Sqlist12.寻找主元素,即一个大小为n的数组中相同元素个数大于n/2的元素

#include <iostream>
using namespace std;
//任务:寻找主元素,即一个大小为n的数组中相同元素个数大于n/2的元素
#define Initsize 50
typedef struct {
	int* data;
	int length, maxsize;
}SqList;
//初始化
void Init(SqList& L)
{
	int i;
	L.data = new int[Initsize];
	for (i = 0; i < 8; i++)
	{
		cin >> L.data[i];

	}
	L.length = i;

}
//相同元素个数必然大于不同元素个数
//假定第一个遇到的元素为主元素c,将它计数为1,如果第二个元素与他相同则计数加1,不同则减1,
//当计数等于0时,将下一个元素假定为主元素c
//若最后计数结果大于0,则这个元素c有可能是主元素,需要验证
//验证,遍历,计算等于c的元素个数,若大于n/2,则是主元素,否则返回-1
int Majority(SqList& L)
{
	int count = 1, c=L.data[0];
	for (int i = 0; i < L.length; i++)
	{
		if (L.data[i] == c)
			count++;
		else
			count--;
		if (count == 0)
		{
			c = L.data[i]; count = 1;
		}
	}
	if (count > 0)
	{
		count = 0;
		for (int i = 0; i < L.length; i++)
			if (L.data[i] == c)
				count++;
	}
	if (count > L.length / 2)
		return c;
	else
		return -1;

}
int main()
{
	SqList L;
	Init(L);
	cout<<Majority(L);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值