一个数组A中存有 n 个整数,在不允许使用另外数组的前提下,将每个整数循环向右移 M( M >=0)个位置,即将A中的数据由(A0 A1 ……AN-1 )变换为(AN-M …… AN-1 A0 A1 ……AN-M-1 )(最后 M 个数循环移至最前面的 M 个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
数据范围:
,
进阶:空间复杂度
,时间复杂度
6,2,[1,2,3,4,5,6]
[5,6,1,2,3,4]
4,0,[1,2,3,4]
[1,2,3,4]
(1<=N<=100,M>=0)
int* solve(int n, int m, int* a, int aLen, int* returnSize ) { // write code here * returnSize=aLen; int i = 0; while(m--) { int t = a[n-1]; for(i=n-2;i>=0;i--) { a[i+1]=a[i]; } a[0]=t; } return a; }
int* solve(int n, int m, int* a, int aLen, int* returnSize ) { // write code here m = m%n; *returnSize = aLen; int last,temp; for(int i=0; i<m; i++){ { last=a[aLen-1]; //先保存最后一个元素 for(int j=aLen-1; j>0; j--){ //从倒数第二个开始,依次把元素赋给下一个,相等于除了最后一个元素,整体右移 a[j] = a[j-1]; } a[0] = last; //将原数组最后一个元素赋值给首位 } } return a; }
int* solve(int n, int m, int* a, int aLen, int* returnSize ) { // write code here int *p=(int*)malloc(sizeof(int)*n); int *temp=(int*)malloc(sizeof(int)*n); int i=0,j=0; *returnSize=n; if(m>n){ m=m%n; } for(i=0;i<m;i++){ temp[i]=a[n-m+i]; } for(j=0;j<n-m;j++){ p[j+m]=a[j]; } for(j=0;j<m;j++){ p[j]=temp[j]; } return p; }