7-1 求最大、次大和第3大的值 (25 分)
本题目要求读入n个整数,要求用最少的比较次数,输出它们的最大值、第2大的值和第3大的值。例如,对于13 13 1 10 34
10这6个数,最大值为34,第2大的值为13,第3大的值为10。
输入格式:
输入有两行。第一行为整数个数n(≤1 000 000),第二行给出n个以空格分隔的整数。
输出格式:
对每一组输入,在一行中输出最大值、第2大的值和第3大的值值,中间以一个空格分隔,但行尾没有多余空格。
如果输入数据不足三个,则输出“Invalid Input”。 如果没有第3大的值,则输出“There is no third largest
element”。 如果没有第2大和第3大的值,则输出“There is no second largest and third
largest element”。
输入样例:
6
13 13 1 10 34 10
输出样例:
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]);
}