1008 数组元素循环右移问题 (20 分)——优化


输入格式:
每个输入包含一个测试用例,第1行输入N(1≤N≤100)和M(≥0);第2行输入N个整数,之间用空格分隔。

输出格式:
在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

1
2
6 2
1 2 3 4 5 6

输出样例:

1
5 6 1 2 3 4

题目链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
scanf("%d %d", &n, &m);
// printf("m=%d", m);
vector<int> arr(n + 1);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
while (m--) {
for (int i = (n - 1); i != -1; i--) {
arr[i + 1] = arr[i];
}
arr[0] = arr[n];
arr[n] = 0;
// for (auto it = arr.begin(); it != arr.end(); it++) {
// printf("%d ", *it);
// }
// printf("\n");
}
arr.resize(n);
n--;
for (auto it = arr.begin(); it != arr.end(); it++) {
printf("%d", *it);
if (n--) printf(" ");
}
printf("\n");
return 0;
}

来自柳神的解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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;
}

更简单的做法,来自Github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include
using namespace std;

int n;
int m;
int main (){
cin >> n >> m;
int q[n];
int flag = 0;
m = m % n;

for (int i = m ; i < n ; i ++) {
cin >> q[i];
if (i == n - 1 && flag == 0) i = -1 , flag = 1; //读入的时候就进行换位置 直接移到应该到的位置去
if (i == m - 1 && flag == 1) break; //flag 的意思是当读到数组末尾的时候重q[0] 开始读入
}
for (int i = 0 ; i < n ; i ++) {
if (i != 0) cout << " " ;
cout << q[i];
}
cout << endl ;
return 0;
}