Problems array elements 1008 rotate right (20 minutes)
An array A, there N (> 0) integer, the premise is not allowed use of additional arrays, each of the integer to the right cycle M (≥0) position, i.e. by data A (A0A1
⋯ A N-1) is converted into (M-⋯ A N A N A. 1-A. 1 0 ⋯ N-A-M. 1
) (final the number of cycles to move the foremost M M positions). If you need to consider the number of times a program to move data as little as possible, to how to design a way to move?
Input format:
Each input comprises a test case, the first input line N (1≤N≤100) and M (≥0); a second input line N integers, separated by spaces in between.
Output format:
output sequence of integers in line right after the M-bit cyclic, separated by a space between, the end of the sequence can not have extra space.
Sample input:
6 2
1 2 3 4 5 6
Sample output:
5 6 1 2 3 4
This method is a little tricky mean, however, meet the requirements of the subject, and did not move (mobile number data is 0).
Where (most likely missed a 3-point test wrong answer ), shift bit number M is greater than the number of array elements N
Solution: Add a M = M% N output before;
#include <stdio.h>
int main()
{
int N,M;
scanf("%d %d",&N,&M);
int a[101];
for(int i=0;i<N;i++)
scanf("%d",&a[i]);
if(N<M)
M=M%N; //移动位数大于数组元素个数的情况,容易被忽略(注意)
for(int j=N-M;j<N;j++)
printf("%d ",a[j]);
for(int k=0;k<N-M-1;k++)
printf("%d ",a[k]);
printf("%d\n",a[N-M-1]);
}
/*这个方法有点取巧的意思,不过符合题目要求,并且完全没有移动(移动数据次数为0)。*/
/*一个最可能被遗漏的情况(2、3测试点答案错误),移动位数M大于数组元素个数N的情况*/
/*解决方法:输出前加上一句M=M%N*/