当前位置:网站首页>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;
}

边栏推荐
- In the SQL SERVER database, if the data of the table is added, deleted, or modified, will the index of the table be recorded in the ldf log?
- 解决win10win7win8系统找不到指定的模块,注册不了大漠插件的问题
- 时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)
- Is the write performance of raid5 faster than raid10?
- js函数聚合的三种实现方式
- 硬件工程师90天学习资料及笔记汇总
- How AliExpress sellers seize product search weight
- Linux下载安装MySql
- StringUtils的具体操作
- iwemeta元宇宙:阿里首任COO:如何打造销售铁军
猜你喜欢

时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)

90.(cesium之家)cesium高度监听事件

nrm 使用详解

PLSQL学习第四天
【一起学Rust | 进阶篇 | RMQTT库】RMQTT消息服务器——安装与集群配置

Uni-app开发微信小程序使用本地图片做背景图

高性能短连接设计

同步锁synchronized追本溯源

NPU架构与算力分析

Solve the problem that the win10win7win8 system cannot find the specified module and cannot register the desert plug-in
随机推荐
phpstudy starts automatically
1-31部 1-31套 和硬件工程师90天学习资料及笔记汇总
placeholder 1
iwemeta元宇宙:一个娃娃卖9999元,泡泡玛特认为一点也不贵
自动化测试框架Pytest(一)——入门
硬件工程师90天学习资料及笔记汇总
StringUtils的具体操作
In the SQL SERVER database, if the data of the table is added, deleted, or modified, will the index of the table be recorded in the ldf log?
90. (cesium house) cesium height monitoring events
基于sklearn的决策树应用实战
不同的命令行风格
阿里云数据库 RDS SQL Server 版的服务器绑定域名www.cxsdkt.cn.的呢?
编程老手如何在autojs和冰狐智能辅助之间选择?
[机缘参悟-65]:《兵者,诡道也》-7-三十六计解读-败战计
颜色选择器的使用
Based on STC8G2K64S4 single-chip microcomputer to display analog photosensitive analog value through OLED screen
winget package manager
Relaxation class: the boss will martial arts, who also can not hold up against!The charm of six sigma training
时序动作定位 | ASM-Loc:弱监督时序动作定位的动作感知片段建模(CVPR 2022)
【一起学Rust | 进阶篇 | RMQTT库】RMQTT消息服务器——安装与集群配置