一、原题
链接:Training on Two Oldest Ages | Codewars
The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age] . |
二、解题
1、分析
找出年龄最大的和年龄第二大的
2.思路
1)遍历数组,将年龄最大值存入max
2)遍历数组,逐个比较,将年龄大但与max不同的值,存入min
3)按要求将值存入results【results非函数内创建,函数调度完不会消失】
三、Myway
#include <stdlib.h>
//result is an output buffer which has to be filled with the solution
void two_oldest_ages(size_t n, const int ages[n], int result[2]) {
// <---- hajime!
int min=-100000,max=-100000;
for(int i=0;i<n;i++){
if(max<ages[i]) max=ages[i];
}
for(int i=0;i<n;i++){
if(min<ages[i] & ages[i]!=max) min=ages[i];
}
result[0]=min;
result[1]=max;
}