我需要从n个数字中识别最大的三个元素,而不使用数组,列表结构,我不应该使用任何排序逻辑。我在C程序中完成了这样的事情。有没有办法更有效地做到这一点?。
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
int number;
scanf("%d",&number);
int firstMax, secondMax, thirdMax;
firstMax = secondMax = thirdMax =number;
for(int i = 1; i<n ; i++){
scanf("%d",&number);
if(number > firstMax){
thirdMax = secondMax;
secondMax = firstMax;
firstMax = number;
}
else if(number > secondMax){
thirdMax = secondMax;
secondMax = number;
}
else if(number > thirdMax){
thirdMax = number;
}
}
printf("%d %d %d",firstMax, secondMax, thirdMax);
return 0;
}
答案 0 :(得分:2)
您可以从与thirdMax
进行比较开始。如果这是错误的,则不需要考虑所有其他的。
if (number > thirdMax)
{
if (number > secondMax)
{
thirdMax = secondMax;
if (number > firstMax )
{
secondMax = firstMax;
firstMax = number;
}
else
{
secondMax = number;
}
}
else
{
thirdMax = number;
}
}