额外空间
多次逆序
环型替换
class Solution {
public:
vector<int> solve(int n, int m, vector<int>& a) {
m = m % n; // 循环右移n位数组元素不变
if(m == 0){
return a;
}
int swap_count=0;
int i=0, tmp, old_tmp;
while(swap_count < n){
int prev = i, next;
tmp = a[prev];
old_tmp = tmp;
do{
next = (prev + m) % n;
tmp = a[next];
a[next] = old_tmp;
prev = next;
old_tmp = tmp;
swap_count ++;
}while(next != i);
i++;
}
return a;
}
};