0 结果
1 题目
2 思路
2.1 思路1(暴力解:另设数组再移动)
原序列保存在数组A中,设另一个数组B,将 A 0 , A 1 , . . . A p − 1 A_0,A_1,...A_{p-1} A0,A1,...Ap−1放到 B n − p , B n − p + 1 , . . . , B n − 1 B_{n-p},B_{n-p+1},...,B_{n-1} Bn−p,Bn−p+1,...,Bn−1中,再将 A p , A p + 1 , A n − 1 A_{p},A_{p+1},A_{n-1} Ap,Ap+1,An−1放到 B 0 , B 1 , . . . , B n − p − 1 B_{0},B_{1},...,B_{n-p-1} B0,B1,...,Bn−p−1中。
#include <cstdio>
#include <cstdlib>
const int n = 6;//数组大小
int* ans(int* L, int p, int n){
int* B = (int*) malloc(sizeof (int) *n);
for(int i = 0;i < p;i++)
B[n - p + i] = L[i];
for(int i = p, j = 0;i < n;i++,j++)
B[j] = L[i];
return B;
}
int main(){
int* R;
R = (int*)malloc(sizeof(int) * n);
for (int i = 0; i < n; ++i) {
*(R + i) = i + 1;
}
int p = 4;
R = ans(R, p, n);
for (int i = 0; i < 6; ++i) {
printf("%d ", *(R + i));
}
return 0;
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
2.2 思路2(最优解:逆置数组)
倒置数组,将数组从头到尾逆置一遍,再从1到p和p+1到n再分别逆置。
#include <cstdio>
#include <cstdlib>
const int n = 6;//数组大小
void Reverse(int* &L, int l, int r){//倒置数组
for(int i = 0;i < (r - l + 1)/2; i++){
int temp = *(L + (l - 1) + i);
*(L + (l - 1) + i) = *(L + (r - 1) - i);
*(L + (r - 1) - i) = temp;
}
}
void ans(int* &L, int p, int n){//三次倒置
Reverse(L, 1, n);
Reverse(L, 1, p);
Reverse(L, p + 1, n);
}
int main(){
int* R;
R = (int*)malloc(sizeof(int) * n);
for (int i = 0; i < n; ++i) {
*(R + i) = i + 1;
}
int p = 2;
ans(R, p, n);
for (int i = 0; i < 6; ++i) {
printf("%d ", *(R + i));
}
return 0;
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)