题解 | #数组元素反转#
数组元素反转
https://www.nowcoder.com/practice/8c9793ae96974a9ebb153d90ef31d357
折半交换,根据下标之和
为 len-1 进行交换。
#include <iostream> using namespace std; int main() { int arr[6] = { 0 }; int len = sizeof(arr) / sizeof(int); for (int i = 0; i < len; i++) { cin >> arr[i]; } cout << "["; for (int i = 0; i < len; i++) { if (i == len - 1) { cout << arr[i] << "]" << endl; break; } cout << arr[i] << ", "; } // write your code here...... for (int i = 0; i < len / 2; ++i) { int tmp = arr[i]; arr[i] = arr[len - 1 - i]; arr[len - 1 - i] = tmp; } cout << "["; for (int i = 0; i < len; i++) { if (i == len - 1) { cout << arr[i] << "]" << endl; break; } cout << arr[i] << ", "; } return 0; }
为 len-1 进行交换。