博客
关于我
PAT Basic Level 1008 数组元素循环右移问题 (思维)
阅读量:266 次
发布时间:2019-03-01

本文共 673 字,大约阅读时间需要 2 分钟。

题目链接:

题目描述:

一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0 A1……AN-1)变换为(AN-M …… AN-1 A0 A1……AN-M-1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动方法 ?

输入输出:

输入

6 2

1 2 3 4 5 6

输出

5 6 1 2 3 4

题目分析:

右移问题的算法为 ,对于大小为n 的数组 ,要想移动m位 ,现将 整个数组颠倒 ,再将前m位颠倒 ,最后将后n-m位颠倒。若m>n 则 对m取n的余数即可 ,因为移动倍数位位置不变。

代码:

#include
#include
#include
using namespace std;int main(){ int n,m; cin>>n>>m; vector
arr(n); for(int i=0;i
>arr[i]; } m=m%n;//处理m比n大的情况 if(m!=0) { reverse(arr.begin(),arr.begin()+n);//现将整个数组颠倒 reverse(arr.begin(),arr.begin()+m);//将前m位颠倒 reverse(arr.begin()+m,arr.begin()+n);//将后n-m位 颠倒 } cout<

   

 

转载地址:http://lolx.baihongyu.com/

你可能感兴趣的文章
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>