本文主要是介绍郑轻oj 1159: 最大的两个数(指针专题),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
比较耗时的做法:
#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;
}
这篇关于郑轻oj 1159: 最大的两个数(指针专题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!