1.题目描述
设将n(n> 1)个整数存放到一维数组R中。设计一个在时间和空间两
方面都尽可能高效的算法。将R中保存的序列循环左移p(0<p<n)个位置,即将R中的数据由()变换为().
2.算法思想
先开一个和原数组一样大的空间用来存数组。然后再按照数组下标左移后的规律来依次复制到新的数组,如(0+p)%n = p, (1+p)%n = p+1, (n-1+p)%n = p-1。最后在复制到顺序表的数组中。
时间复杂度:
空间复杂度:
3.代码呈现
顺序表的基本结构操作和详见:https://blog.csdn.net/zfq17796515982/article/details/107140989
主要代码:
void f(SqList &L, int p){
ElemType *temp;
temp = new ElemType[L.length];
for(int i=0;i<L.length;i++){
temp[(i+p)%L.length] = L.data[i];
}
for(int i=0;i<L.length;i++){
L.data[i] = temp[i];
}
}
int main()
{
SqList L;
L.data = new ElemType[MaxSize];
L.length = 0;
int n, p;
cin>>n>>p; // 元素个数和循环左移的位数。
for(int i=0;i<n;i++){
ElemType c; cin>>c;
ListInsert(L, i+1, c);
}
// ListPrint(L);
f(L, p);
ListPrint(L);
return 0;
}
4.运行结果
6 2
1 1 1 2 1 1
1 1 1 1 1 2
5.PS
同时这个问题可以看做倒置数组两部分的变形。 其中,
时间复杂度:
空间复杂度: