HDU1029 Ignatius and the Princess IV(數組中出現次數最多的數)

題目:HDU1029

 

Ignatius and the Princess IV

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32767 K (Java/Others)
Total Submission(s): 44112    Accepted Submission(s): 19470

Problem Description

"OK, you are not too bad, em... But you can never pass the next test." feng5166 says.

"I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers." feng5166 says.

"But what is the characteristic of the special integer?" Ignatius asks.

"The integer will appear at least (N+1)/2 times. If you can't find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha....." feng5166 says.

Can you find the special integer for Ignatius?

Input

The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.

Output

For each test case, you have to output only one line which contains the special number you have found.

Sample Input

5 1 3 2 3 3 11 1 1 1 1 1 5 5 5 5 5 5 7 1 1 1 1 1 1 1

Sample Output

3 5 1

 

方法一:

先將所有數輸入一個數組,然後用sort函數排序,最後找出出現次數最多的數。我自己做的時候最後一步又是用結構體,又是用數組,其實只要一趟遍歷就行了。

代碼:

#include <iostream>
#include <algorithm>
using namespace std;

int a[1000000];

int main()
{
	int n;
	while (cin >> n)
	{
		for (int i = 0; i < n; i++)
			cin >> a[i];
		sort(a, a + n);
		
		int value, mmax, count = 1;
		value = a[0];
		mmax = 0;
		for (int i = 1; i < n; i++)
		{
			if (a[i] == a[i-1])
				count++;
			else
			{
				if (count > mmax)
				{
					mmax = count;
					value = a[i-1];
				}
				count = 1;
			}
		}
		if (count > mmax)
		{
			mmax = count;
			value = a[n-1];
		}
		
		cout << value << endl;
	}
	
	return 0;
}

 

方法二:

其實第一次排完序之後,直接輸出數組下標爲 (n + 1) / 2 的元素就是正確答案。因爲這個數至少出現 (n + 1) / 2 次,所以排完序後改下標的元素必定是所求元素。

代碼:

#include <iostream>
#include <algorithm>
using namespace std;

int a[1000000];

int main()
{
	int n;
	while (cin >> n)
	{
		for (int i = 0; i < n; i++)
			cin >> a[i];
		sort(a, a + n);
		
		
		cout << a[(n+1)/2] << endl;
	}
	
	return 0;
}

 

方法三:

上面兩種方法都基本是O(nlogn),而這個方法是O(n)
設置一標誌量num,按照原順序依次迭代,隨便假定一個解,如果num==ans,time++,否則time–,當time爲0時將當前num作爲新解。因爲n爲奇數,且特殊值出現次數大於一半,所以任何情況下,特殊值做爲解時的time不會小於1,所以最終的解一定就是特殊值。

代碼:

#include <iostream>
using namespace std;
 
int main()
{
	int n;
 
	while (cin >> n)
	{
		int time = 0, ans, num;
 
		while (n--)
		{
			cin >> num;
 
			if (time == 0)
			{
				ans = num;
				time++;
			}
			else
			{
				if(num == ans)
					time++;
				else
					time--;
			}
		}
 
		cout << ans << endl;
	}
 
	return 0;
}

 

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