我需要从n个数字中找出最大的3个元素,而不需要使用数组、类似列表的结构,也不应该使用任何排序逻辑,我在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;
}
最佳答案
您可以从比较thirdMax
开始。如果这是错误的,则不必考虑所有其他因素。
if (number > thirdMax)
{
if (number > secondMax)
{
thirdMax = secondMax;
if (number > firstMax )
{
secondMax = firstMax;
firstMax = number;
}
else
{
secondMax = number;
}
}
else
{
thirdMax = number;
}
}
关于c - n个数字中最大的三个数字而不使用数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47248231/