天天看點

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

繼續閱讀