题目:把一个含有N个元素的数组循环右移k位,要求时间复杂度为O(n),只许使用两个附加变量。
#include <iostream>
#include <vector>
using namespace std;
int Reverse(int *a,int left,int right) {
for(;left<right;left++,right--){
int temp=a[left];
a[left]=a[right];
a[right]=temp;
}
}
int RightShift(int *a,int N,int k){
k=k%N;
Reverse(a,0,N-k-1);
Reverse(a,N-k,N-1);
Reverse(a,0,N-1);
}
int Print(int *a,int N){
if(a){
for(int i=0;i<N;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
}
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
Print(a,10);
RightShift(a,10,4);
Print(a,10);
return 0;
}