B1008 数组元素循环右移问题 (20分)
思路
1 2 3 4 5 6
5 6 1 2 3 4
6个数,循环右移2位。
也可以理解为
先翻转
6 5 4 3 2 1
然后再两部分,分别翻转
5 6 1 2 3 4
AC代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
m %= n;
if (m != 0) {
reverse(begin(a), begin(a) + n);
reverse(begin(a), begin(a) + m);
reverse(begin(a) + m, begin(a) + n);
}
for (int i = 0; i < n - 1; i++)
cout << a[i] << " ";
cout << a[n - 1];
return 0;
}
另一种AC代码
#include <stdio.h>
int main() {
int a[110];
int n, m, count = 0;
scanf("%d%d", &n, &m);
m = m % n;
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for(int i = n - m; i < n; i++) {
printf("%d", a[i]);
count++;
if(count < n) printf(" ");
}
for(int i = 0; i < n - m; i++) {
printf("%d", a[i]);
count++;
if(count < n) printf(" ");
}
return 0;
}
原文地址:https://www.cnblogs.com/lingr7/p/10298381.html
时间: 2024-10-02 08:08:42