额外空间

多次逆序

环型替换

  1. class Solution {
  2. public:
  3. vector<int> solve(int n, int m, vector<int>& a) {
  4. m = m % n; // 循环右移n位数组元素不变
  5. if(m == 0){
  6. return a;
  7. }
  8. int swap_count=0;
  9. int i=0, tmp, old_tmp;
  10. while(swap_count < n){
  11. int prev = i, next;
  12. tmp = a[prev];
  13. old_tmp = tmp;
  14. do{
  15. next = (prev + m) % n;
  16. tmp = a[next];
  17. a[next] = old_tmp;
  18. prev = next;
  19. old_tmp = tmp;
  20. swap_count ++;
  21. }while(next != i);
  22. i++;
  23. }
  24. return a;
  25. }
  26. };