出現次數超過一半的數字

題目:數組中有一個數字出現的次數超過了數組長度的一半,找出這個數字。

            詳見《編程之美》的2.3尋找發帖水王。

#include <iostream>
using namespace std;

int Find(int *a, int N)//出現次數超過一半的數字
{
	int candidate;
	int nTimes, i;

	for(i=nTimes=0; i<N; i++)
	{
		if(nTimes==0)
		{
			candidate=a[i];
			nTimes=1;
		}
		else
		{
			if(candidate==a[i])
				nTimes++;
			else
				nTimes--;
		}
	}
	return candidate;
}

void main()
{
	int a[5]={0,1,2,1,1};
	cout<<Find(a, 5)<<endl;
}


 

 

 

發佈了90 篇原創文章 · 獲贊 22 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章