week12-A-Required questions-1

topic

Given n numbers, zjm wants to find the number that appears at least (n+1)/2 times. Now I need your help to find out what is this number?

Input

This question contains multiple sets of data:

Each set of data contains two rows.

There is a number N (1<=N<=999999) in the first line, and ensure that N is an odd number.

The second line is N integers separated by spaces.

The data ends with EOF.

Output

For each set of data, you need to output the unique number you find.

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

Ideas

Use map to record the number of appearances corresponding to each number, and judge whether the number of appearances of the number is >=(n+1)/2 while entering it, output it immediately when it is satisfied, and receive and discard the remaining characters.

error

1. Note that the data may not be recorded completely after the break in for
2. Note that only n characters are received when receiving, so i++ must be used after the break to continue counting the number of characters entered.
3. Note that the received number may be of long long type

Code

#include<iostream>
#include<map> 
using namespace std;
int main()
{
    
    
	int n;
	while(scanf("%d",&n)!=EOF)
	{
    
    
		map<long long,int> num;
		int i=0; 
		long long tmp;
		for(i=0;i<n;i++)
		{
    
    
			cin>>tmp;
			num[tmp]++;
			if(num[tmp]>=(n+1)/2)
			{
    
    
				cout<<tmp<<endl;
				break;				
			}
		}
		i++;
		for(;i<n;i++)
			cin>>tmp;
}
	return 0;
}

Guess you like

Origin blog.csdn.net/alicemh/article/details/106130491