尋找多數元素---算法設計課堂記錄

多數元素的定義:在n個元素中之後有n/2個同一個元素,那麼就稱這個元素爲多數元素

#include <iostream>
using namespace std;

const int maxN=50;//capacity
const int none=-1;

int a[maxN];
int n;//number

int candidate(int x)//check a[x] is major ?
{
	int j=x,c=a[x],count=1;//j is pointer
	while(j<n&&count>0)//this circle will erase 2n pairs of different elements
	{
		j++;
		if(a[j]==c)
			count++;
		else
			count--;//erase the element which show up for too little time
	}//if end up becase count is 0 then we need give up the element
	if(j==n)
		return c;
	else return candidate(j+1);
}

int search()
{
	//the funtion of candidate:return the majority value 
	int c=candidate(1);
	int count=0;
	//check
	for(int j=1;j<=n;j++)
	{
		if(a[j]==c)
			count++;
	}
	if(count>n/2)
		return c;
	else
		return none;	
}

int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	int ans=search();
	cout<<ans;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章