比较耗时的做法:
#include <stdio.h>
void LargestTow(int a[],int n,int *pfirst,int *psecond)
{
int max = 0;
*pfirst = a[0];;
for (int i = 1; i < n; ++i)
{
if (a[i] > *pfirst)
{
*pfirst = a[i];
max = i;
}
}
for (int i = max; i < n - 1; ++i)
a[i] = a[i + 1];
*psecond = a[0];
for (int i = 0; i < n - 1; ++i)
if (a[i] > *psecond) *psecond = a[i];
}
int main()
{
int n, a[1010], x, y;
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
LargestTow(a, n, &x, &y);
printf("%d %d", x, y);
return 0;
}
省时间是做法:
#include <iostream>
#include <algorithm>
using namespace std;
void LargestTow(int a[],int n,int *pfirst,int *psecond)
{
*pfirst = a[0], *psecond = a[1];
if (*psecond > *pfirst) swap(*psecond, *pfirst);
for (int i = 1; i < n; ++i)
{
if (a[i] > *pfirst)
{
*psecond = *pfirst;
*pfirst = a[i];
}
else if (a[i] > *psecond) *psecond = a[i];
}
}
int main()
{
int n, a[1010], first = 0, second = 0;
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
LargestTow(a, n, &first, &second);
printf("%d %d", first, second);
return 0;
}