C++ 移动数组元素:将最小值和最大值交换到数组首尾 - 算法题解
C++ 移动数组元素:将最小值和最大值交换到数组首尾
本题要求在给定的不重复整数数组中,将最小值和数组第一个数交换,最大值和数组最后一个数交换。
题目描述
在一个不重复的数组中,请将这个数组的最小数和数组第一个数交换,最大数和数组最后一个数交换!
输入描述
有两行
第一行有一个整数n ( 5 <= n <= 100 )
第二行有n个不重复的整数!
输出描述
移动位置后的数组!
用例输入 1
5 6 7 1 10 4
用例输出 1
1 7 6 4 10
代码实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> arr(n);
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
int minIndex = min_element(arr.begin(), arr.end()) - arr.begin();
int maxIndex = max_element(arr.begin(), arr.end()) - arr.begin();
swap(arr[0], arr[minIndex]);
swap(arr[n-1], arr[maxIndex]);
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
代码解析
1. 使用 min_element 和 max_element 函数分别找到数组中的最小值和最大值的位置。
2. 使用 swap 函数将最小值和数组第一个元素交换,将最大值和数组最后一个元素交换。
3. 循环遍历数组,输出每个元素。
总结
本题主要考察了 C++ 数组的遍历、元素交换、最小值和最大值查找等基本操作。代码实现简洁易懂,适合初学者学习。
原文地址: https://www.cveoy.top/t/topic/qmCZ 著作权归作者所有。请勿转载和采集!