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
同時這個問題可以看做倒置數組兩部分的變形。 其中,
時間複雜度:
空間複雜度: