博客
关于我
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/

你可能感兴趣的文章
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+tomcat单个域名及多个域名配置
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
nginxWebUI runCmd RCE漏洞复现
查看>>
nginx_rtmp
查看>>
Nginx、HAProxy、LVS
查看>>
nginx一些重要配置说明
查看>>
Nginx下配置codeigniter框架方法
查看>>