题解 | #互换最大最小数#

互换最大最小数

https://www.nowcoder.com/practice/04c0f21530994fbfa94887f1e3588e6a

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <map>
#include <queue>
#include <cmath>
using namespace std;

int main() {
    int n;
    int maxIndex = 0, minIndex = 0; //这里一定要赋初值
    int maxnum, minnum;
    int arr[30];
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }
        maxnum = arr[0];
        minnum = arr[0];
        for (int i = 1; i < n; i++) {

            if (arr[i] > maxnum) {
                maxIndex = i;
                maxnum = arr[i];
            }
            if (arr[i] < minnum) {
                minIndex = i;
                minnum = arr[i];
            }
        }

        int t = arr[minIndex];
        arr[minIndex] = arr[maxIndex];
        arr[maxIndex] = t;

        for (int i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }

        printf("\n");

    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务