当前位置:网站首页>PTA 习题2.2 数组循环左移
PTA 习题2.2 数组循环左移
2022-08-10 08:24:00 【盖世馒头】
题目
本题要求实现一个对数组进行循环左移的简单函数:一个数组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
1、循环队列法
利用循环队列的思想,可以简单地做出来
#include<stdio.h>
int main(){
int front=0,rear=0,size;
scanf("%d%d",&size,&front);
int arr[size];
rear=front-1;
for(int i=0;i<size;i++)
scanf("%d",&arr[i]);
for(int i=front;i<front+size;i++){
if(i==front)
printf("%d",arr[i%size]);
else
printf(" %d",arr[i%size]);
}
return 0;
}
2、逆转法
分别先对前半部分和后半部分进行逆转,然后再对整个数组进行逆转。
#include<stdio.h>
void reverse(int arr[],int start,int end){
while(start<end){
int temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
}
int main(){
int size,movements;
scanf("%d%d",&size,&movements);
movements=movements%size;
int arr[size];
for(int i=0;i<size;i++)
scanf("%d",&arr[i]);
reverse(arr,0,movements-1);
reverse(arr,movements,size-1);
reverse(arr,0,size-1);
for(int i=0;i<size;i++){
printf("%d",arr[i]);
if(i<size-1)
printf(" ");
}
return 0;
}
边栏推荐
- Different command line styles
- 大体来讲,网站会被攻击分为几种原因
- Add spark related dependencies and packaging plugins (sixth bullet)
- Synchronization lock synchronized traces the source
- Day37 LeetCode
- NPU架构与算力分析
- The sixteenth day & the basic operation of charles
- ShardingSphere入门
- IDLE development wordCount program (5)
- 推荐几个高质量的软件测试实战项目
猜你喜欢
随机推荐
CV+Deep Learning - network architecture Pytorch recurrence series - classification (3: MobileNet, ShuffleNet)
placeholder 1
.NET-7.WPF learning experience summary
Guys, may I ask, the oraclecdc error report is not serialized, but I see that the source code does not inherit serialization, what is the reason?
自动化测试框架搭建 ---- 标记性能较差用例
时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)
Johnson全源最短路
Different command line styles
If the data of the oracle business table is added, deleted, or modified, will the index of the table write redo and undo?
UGUI - Events, iTween Plugin
[机缘参悟-65]:《兵者,诡道也》-7-三十六计解读-败战计
自动化测试框架Pytest(一)——入门
NPU架构与算力分析
VS2013-debug assembly code-generate asm file-structure memory layout-function parameter stack-calling convention
[Learn Rust together | Advanced articles | RMQTT library] RMQTT message server - installation and cluster configuration
2022-08-01 Advanced Network Engineering (24) STP Advanced Knowledge
并查集模板
90. (cesium house) cesium height monitoring events
Rust学习:6.5_复合类型之数组
占位占位1