Assume that n(n~1) integers are stored in a one-dimensional array R. Try to design an
algorithm that is as efficient as possible in terms of time complexity and space complexity, and move the sequence stored in R to the left by p
(0spsn) positions, that is, transform the data in R from (x0x1xn1) to (xp
Xptle .., Xn-1,x0,X1,...,xp1)
void Reverse (int R[], int left, int right){
//将数组原地逆置
int ¡= left, j= right;
while(i<i){
int tmp=R[i];
R[i]= R[j];
R[j]=tmp;
i++; //右移动一个位置
j--; //左移一个位置
}
}
void LeftShift(int R[], int n, int p)
// 将长度为口的数组R中的数据循环左移p个位置
if(p>0 && p≤n){
Reverse(R,0,n-1);
//将数组全部逆置
Reverse(R,0,n-p-1);
//将前 n-p 个数据逆置
Reverse(R,n-p,n-1);
//将后 p个数据逆置
}
}
Suppose there is an array: (321)(654), at this time, n is 6, p is 3;
a: 0-5 reverse. (n-1=5); get(456)(123)
b: 0-2 reverse. (np-1=2); get(654)(123)
c: 3-5 reversal. (654) (321)
n