做题地址:https://pintia.cn/problem-sets?tab=0
C语言在线开发环境:https://clin.icourse163.org/
本题要求实现一个对数组进行循环右移的简单函数:一个数组a中存有n(>0)个整数,将每个整数循环向右移m(≥0)个位置,即将a中的数据由(a0a1⋯an−1)变换为(an−m⋯an−1a0a1⋯an−m−1
)(最后m个数循环移至最前面的m个位置)。
函数接口定义:
int ArrayShift( int a[], int n, int m );
其中a[]是用户传入的数组;n是数组的大小;m是右移的位数。函数ArrayShift须将循环右移后的数组仍然存在a[]中。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
int ArrayShift( int a[], int n, int m );
int main()
{
int a[MAXN], n, m;
int i;
scanf("%d %d", &n, &m);
for ( i = 0; i < n; i++ ) scanf("%d", &a[i]);
ArrayShift(a, n, m);
for ( i = 0; i < n; i++ ) {
if (i != 0) printf(" ");
printf("%d", a[i]);
}
printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
AC代码:
int ArrayShift(int a[], int n, int m) {
m=m%n;//考虑m>n
int str[m];
for(int i = 0; i < m; ++i) {
str[i] = a[n-m+i];
}
for(int i = n-m-1; i >= 0; --i) {
a[m+i] = a[i];
}
for(int i = 0; i < m; ++i) {
a[i] = str[i];
}
return 0;
}
总结:
这个题目的思路也比较简单,我一开始的答案出错在没有考虑m>n的情况;还有一个地方要注意就是第二个for循环,如果写的是for(int i=0;i<n-m;++i)这样的形式,就会出现问题:
若输入:
7 3
1 2 3 4 5 6 7
则输出:
5 6 7 1 2 3 1
原因显而易见。