数组元素循环右移问题

自测-3 数组元素循环右移问题 (20 分)

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

输入格式:

每个输入包含一个测试用例,第1行输入N(1N100)和M(0);第2行输入N个整数,之间用空格分隔。

输出格式:

在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。

输入样例:

6 2
1 2 3 4 5 6

输出样例:

5 6 1 2 3 4

#include <iostream>
#include <deque>
using namespace std;
int main(){
int n, m, temp;
cin >> n >> m;
deque<int> myDeq;
for(int i = 0; i < n; i++){
cin >> temp;
myDeq.push_back(temp);//将数据读入到队列中
}
for(int i = 0; i < m; i++){
int temp1 = myDeq.back();//返回队列最后一个元素
myDeq.pop_back();//删除队列最后一个元素
myDeq.push_front(temp1);//将队列尾的元素添加到队列头
}
for(deque<int>::iterator it = myDeq.begin(); it != myDeq.end(); it++){
if(it == myDeq.begin()){
cout << *it;
}else{
cout << ' ' << *it;
}

}
return 0;
}

 
posted @ 2019-03-05 08:49  kakaluotedj  阅读(171)  评论(0)    收藏  举报