先po上我的代码:
实现一位移位, 然后循环疑问, 时间复杂度是(M*N)的, 近似于N^2吧.......
即使是我的代码打印那里也是抄袭了人家的/xk
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int num[N];
int M;
cin >> M;
M = M % N;
for(int i=0; i!=N; ++i){
cin >> num[i];
}
for(int i=0; i!=M; ++i){
//循环移1位
int temp = num[N-1];
for(int i=N-1; i!=0; --i){
num[i]=num[i-1];
}
num[0] = temp;
}
for(int i=0; i!=N; ++i){
cout<< num[i] << (i-N+1?" ":"\n");
}
return 0;
}
大佬(https://blog.csdn.net/xtzmm1215/article/details/38407799)的答案:
#include <stdio.h>
int a[100];
void reverse(int *a, int m, int n){
for (int i = m; i <= (m + n) / 2; i++){
int tmp = a[i];
a[i] = a[m + n - i];
a[m + n - i] = tmp;
}
}
int main(){
int n, m;
scanf("%d%d", &n, &m);
m %= n;
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
reverse(a, 0, n-m-1);
reverse(a, n-m, n-1);
reverse(a, 0, n-1);
for (int i = 0; i < n; i++)
printf("%d%s", a[i], (i-n+1?" ":"\n"));
return 0;
}
这个算法不得不服啊/V
不过不是很好理解吧....
参阅https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.01.md
这里有很完美的解释