Find the largest, second and third largest values

7-1 Find the largest, second and third largest values ​​(25 points)

This question requires reading n integers, using the least number of comparisons, and outputting their maximum value, the second largest value, and the third largest value. For example, for the
6 numbers 13 13 1 10 34 10, the maximum value is 34, the second largest value is 13, and the third largest value is 10.

Input format:

There are two lines of input. The first line is the number of integers n (≤1 000 000), and the second line gives n integers separated by spaces.

Output format:

For each set of input, output the maximum value, the second largest value, and the third largest value in one line, separated by a space, but there is no extra space at the end of the line.
If the input data is less than three, "Invalid Input" is output. If there is no third largest
element , output "There is no third largest element". If there is no second largest and third
largest value, output "There is no second largest and third largest element".

Input sample:

6
13 13 1 10 34 10

Sample output:

34 13 10

#include<stdio.h>
int main()
{
    
    
	int n,max[3]={
    
    -100000,-100000,-100000},cnt=0;
	scanf("%d",&n);
	if(n<3){
    
    
		printf("Invalid Input\n");
		return 0;
	}//不足三个数据,直接return 0;
	int a[n];
	for(int i=0;i<n;i++)
	{
    
    
		scanf("%d",&a[i]);
	}
	for(int i=0;i<n;i++)
	{
    
    
		if(a[i]>max[0])
		{
    
    
			max[0]=a[i];
			cnt++;
		}
	}
	for(int i=0;i<n;i++)
	{
    
    
		if(a[i]>max[1]&&a[i]<max[0])
		{
    
    
			max[1]=a[i];
			cnt++;
		}
	}
	for(int i=0;i<n;i++)
	{
    
    
		if(a[i]>max[2]&&a[i]<max[1])
		{
    
    
			max[2]=a[i];
			cnt++;
		}
	}
	if(cnt==1)printf("There is no second largest and third largest element");
	else if(cnt==2)printf("There is no third largest element");
	else  printf("%d %d %d",max[0],max[1],max[2]);
}

Guess you like

Origin blog.csdn.net/weixin_51198300/article/details/114652667