天天看点

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

继续阅读