版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37454852/article/details/85342290
1008 数组元素循环右移问题 (20 分)
一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数据由(A
0
A
1
⋯A
N−1
)变换为(A
N−M
⋯A
N−1
A
0
A
1
⋯A
N−M−1
)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:
每个输入包含一个测试用例,第1行输入N(1≤N≤100)和M(≥0);第2行输入N个整数,之间用空格分隔。
输出格式:
在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6 1 2 3 4
#include <cstdio>
#include <cstring>
#include <cmath>
//数据结构里的经典题目了,刚开始还想了半天,惭愧惭愧
int A[110] = { 0 };
void reverse(int l, int r)//把A的l~r翻转
{
while(l<r)
{
int temp = A[l];
A[l] = A[r];
A[r] = temp;
l++, r--;
}
}
int main()
{
int N = 0, M=0;
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
{
scanf("%d", &A[i]);
}
M = M % N;//不加这句有两个点测试不通过,还是要考虑周到些(M可能大于N!)
reverse(0, N - 1);//三次翻转即可
reverse(0, M-1);
reverse(M, N-1);
if( N ) printf("%d", A[0]);
for (int i = 1; i < N; i++)
{
printf(" %d", A[i]);
}
return 0;
}