[leetcode] Rotate Array

Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
 
空间复杂度为O(1)。
 
 1 class Solution
 2 {
 3 public:
 4   void rotate(int nums[], int n, int k)
 5   {
 6     if(k == 0 || k == n)
 7       return;
 8 
 9     if(k > n)
10       k = k - n;
11 
12     int m = 0;
13     for(int i=0; i<k; i++)
14     {
15       m = nums[n-i-1];
16       for(int j=n-i-1; j>=0;)
17       {
18         if(j-k >= 0)
19           nums[j] = nums[j-k];
20         else
21           nums[j] = m;
22 
23         j -= k;
24       }
25     }
26 
27     int len = n % k;
28     if(len != 0)
29       rotate(nums, k, k - len);
30   }
31 };
原文地址:https://www.cnblogs.com/lxd2502/p/4313745.html