7-2 数组循环左移 (20 分)
本题要求实现一个对数组进行循环左移的简单函数:一个数组a中存有n(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向左移m(≥0)个位置,即将a中的数据由(a0a1⋯an−1)变换为(am⋯an−1a0a1⋯am−1)(最前面的m个数循环移至最后面的m个位置)。如果还需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:
输入第1行给出正整数n(≤100)和整数m(≥0);第2行给出n个整数,其间以空格分隔。
输出格式:
在一行中输出循环左移m位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
8 3
1 2 3 4 5 6 7 8
结尾无空行
输出样例:
4 5 6 7 8 1 2 3
结尾无空行
第一次通过使用的是数组,思路是从第m个数开始读,读到n后从0读到m-1。
代码如下:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,k;
scanf("%d %d",&n,&k);
int *a = (int *)malloc(sizeof(int)*n);
for(i = 0;i < n;i++)
{
scanf("%d",&a[i]);
}
k %= n;
for(i = k;i < n;i++)
{
if(i == k){
printf("%d",a[i]);
}
else{
printf(" %d",a[i]);
}
}
for(i = 0;i < k;i++){
printf(" %d",a[i]);
}
return 0;
}
本题也可以采用循环链表解决:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
int next;
}node;
int main(void){
int i,n,m;
scanf("%d %d",&n,&m);
m = m%n;
struct Node *p = (struct Node *)malloc(sizeof(struct Node)*n);
for(i = 0;i < n-1;i++){
scanf("%d",&p[i].data);
p[i].next = i+1;
}
scanf("%d",&p[n-1].data);
p[n-1].next = 0;
int count;
for(i = m,count = 0;count<n;count++){
printf("%d",p[i].data);
i = p[i].next;
if(count != n-1){
printf(" ");
}
}
return 0;
}
此外,本题可以采用逆置算法,此题可以通过三次reverse(first,last)函数实现,实现反转从first
到last
(不含)之间的元素(不含last的原因为数组从0开始,最后一个元素为last-1)
通过3次reverse实现将数组 A[n] 中所有元素循环左移 k 个位置:
reverse(a, a + k)
reverse(a + k, a + n)
reverse(a, a + n)
具体reverse代码为:
void Reverse(int *first, int *last)
{
last--;
for (int temp; first < last; first++, last--)
temp = *first, *first = *last, *last = temp;
}
完整代码为:
#include<stdio.h>
void reverse(int *first,int *last){
last--;
for(int temp;first<last;first++,last--){
temp = *first;
*first = *last;
*last = temp;
}
}
int main(void){
int i,m,n;
scanf("%d %d",&n,&m);
int *a = malloc(sizeof(int)*n);
m = m%n;
for(i = 0;i<n;i++){
scanf("%d",&a[i]);
}
reverse(a,a+m);
reverse(a+m,a+n);
reverse(a,a+n);
for(i = 0;i<n;i++){
if(i == 0){
printf("%d",a[i]);
}
else{
printf(" %d",a[i]);
}
}
return 0;
}
时间复杂度为O(n)
原理:
设将 n 个整数存放到一维数组 R 中
- 首先,将数组分为两部分 a、b,a 表示前 p 个元素,b 代表剩下的元素;
- 那么原问题就可以看作是:将数组
转换成
;
- 然后,将数组 R 中的 a、b 分别逆置得到
;
- 然后对
整体逆置就可以得到
;
举个例子:
将 abcdefg 循环左移 3 位:
- 将 abcdefg 分成 abc、defg 两部分;
- 然后将两部分分别逆置然后组合得到 cba gfed;
- 再将 cba gfed 整体逆置就可以得到 defgabc;
- 这样就完成了将 abcdefg 循环左移 3 位;
思路参考https://blog.csdn.net/qq_27775515/article/details/114830672,数组循环左移最优算法:逆置算法感谢。