本題要求實現一個對數組進行循環左移的簡單函數:一個數組a中存有n(>)個整數,在不允許使用另外數組的前提下,將每個整數循環向左移m(≥)個位置,即將a中的數據由(a0a1⋯an−1)變換為(am⋯an−1a0a1⋯am−1)(最前面的m個數循環移至最后面的m個位置)。如果還需要考慮程序移動數據的次數盡量少,要如何設計移動的方法?
輸入格式:
輸入第1行給出正整數n(≤)和整數m(≥);第2行給出n個整數,其間以空格分隔。
輸出格式:
在一行中輸出循環左移m位以后的整數序列,之間用空格分隔,序列結尾不能有多余空格。
輸入樣例:
8 3
1 2 3 4 5 6 7 8
輸出樣例:
4 5 6 7 8 1 2 3
#include<iostream> #include<stdio.h> using namespace std; void reverse(int a[], int lo,int hi)//數組逆轉函數 { int i=lo,j = hi; while(i<j) { int temp = a[i]; a[i] = a[j]; a[j]=temp; i++; j--; } } int main() { int n,m; scanf("%d %d",&n,&m); m = m%n;//取余數,當m>n時,移動m%n次和移動m次效果一樣 int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } reverse(a,0,n-1);//逆轉三次德最后結果 reverse(a,0,n-m-1); reverse(a,n-m,n-1); for(int i=0;i<n;i++) { printf("%d",a[i]); if(i<n-1) { printf(" "); } } return 0; }