当前位置:   article > 正文

郑轻oj 1159: 最大的两个数(指针专题)_1159: 最大的两个数(指针专题)

1159: 最大的两个数(指针专题)

 比较耗时的做法:

  1. #include <stdio.h>
  2. void LargestTow(int a[],int n,int *pfirst,int *psecond)
  3. {
  4. int max = 0;
  5. *pfirst = a[0];;
  6. for (int i = 1; i < n; ++i)
  7. {
  8. if (a[i] > *pfirst)
  9. {
  10. *pfirst = a[i];
  11. max = i;
  12. }
  13. }
  14. for (int i = max; i < n - 1; ++i)
  15. a[i] = a[i + 1];
  16. *psecond = a[0];
  17. for (int i = 0; i < n - 1; ++i)
  18. if (a[i] > *psecond) *psecond = a[i];
  19. }
  20. int main()
  21. {
  22. int n, a[1010], x, y;
  23. scanf("%d", &n);
  24. for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
  25. LargestTow(a, n, &x, &y);
  26. printf("%d %d", x, y);
  27. return 0;
  28. }

省时间是做法:

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. void LargestTow(int a[],int n,int *pfirst,int *psecond)
  5. {
  6. *pfirst = a[0], *psecond = a[1];
  7. if (*psecond > *pfirst) swap(*psecond, *pfirst);
  8. for (int i = 1; i < n; ++i)
  9. {
  10. if (a[i] > *pfirst)
  11. {
  12. *psecond = *pfirst;
  13. *pfirst = a[i];
  14. }
  15. else if (a[i] > *psecond) *psecond = a[i];
  16. }
  17. }
  18. int main()
  19. {
  20. int n, a[1010], first = 0, second = 0;
  21. cin >> n;
  22. for (int i = 0; i < n; ++i) cin >> a[i];
  23. LargestTow(a, n, &first, &second);
  24. printf("%d %d", first, second);
  25. return 0;
  26. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/143781
推荐阅读
相关标签
  

闽ICP备14008679号