Programming Training - Modes

mode

Program Design 2020-2021 Summer Semester Training

1. Topic description

The number that appears the most in a set of data is called the mode. for example

1 2 3 3

The mode is 3. There may also be multiple modes in a set of data, and the mode that appears first is taken as the mode. for example

2 2 3 3

The mode is 2.

The problem is a set of data sorted in ascending order, indicating its mode.

2. Input form

There are multiple sets of test data (no more than 100 sets of test data).

Each set of test data occupies two lines, and the first line is a positive integer N: indicating the number of data items in this set of test data.

The second line is N positive integers separated by spaces, representing the data elements of this set of test data. Each data element is no greater than 10000.

N=0, which means the input is over and no processing is required.

40% of the test data N 1 ≤ N ≤ 10;

30% of the test data N 10 < N≤ 100;

20% of the test data N 100 < N≤ 1000;

10% of test data N 1000 < N≤ 10000;

test case

【Sample input】

4
1 2 3 3
4
2 2 3 3
0
【Sample output】

3
2

topic analysis

This question is not difficult, you only need to create an array to count the number of occurrences of each number. Below is the code~

the code

The code is as follows (example):

#include<bits/stdc++.h>
using namespace std;
void fun(int n)
{
    
    
	int a[10001];
	memset(a,0,sizeof(a));
	int k=0;
	for(int i=0;i<n;i++)
	{
    
    
		int j=0;
		cin>>j;
		a[j]++;
	}
	int max=0;
	for(int i=0;i<10001;i++)
	{
    
    
		if(a[i]>max)
		{
    
    
			max=a[i];
			k=i;
		}
	}
	cout<<k<<endl;
	
}
int main()
{
    
    
	int n;
	while(cin>>n)
	{
    
    
		if(n==0)
		break;
		else
		fun(n);
	 } 
	return 0;
 } 

Guess you like

Origin blog.csdn.net/weixin_51295681/article/details/118491945