class Solution {
public:
void rotate(int nums[], int n, int k) {
int nowIndex = 0, nextIndex;
int tmp1, tmp2 = nums[0];
for(int j=0,i=0; j<n; j++){
tmp1 = tmp2;
nowIndex = (k + nowIndex) % (n);
tmp2 = nums[nowIndex];
nums[nowIndex] = tmp1;
if(nowIndex == i) {
nowIndex = ++i;
tmp2 = nums[nowIndex];
}
}
}
};
My c++ solution, o(n)time && o(1)space


Excellent Answer. Here I just add some explanations.
How to change [0,1,2,3,4,5,6] to [4,5,6,0,1,2,3] by k = 3?
We can change by following rules: [0]>[3], [1]>[4], [2]>[5], [3]>[6], [4]>[0], [5]>[1], [6]>[2]
Other cases are the same.
To solve this problem, we should know the following two facts:

We must do exactly n assignedsteps to finish the target.
see the two figures below. On the right side of each figure shows the same process as left side. The total step is just the number of edges.

We can obtain several selfclosed circles when we do the operation.
By figure we can clearly see it. Each time when we exchange values among a circle, there is no relationship with other circles.Done with this one, we move to another circle.
class Solution { public: void rotate(int nums[], int n, int k) { if(n == 0)return; k = k % n; //initialize int i = 0; int nowIndex = 0; int tmp = nums[0],stmp; //exactly n steps, n times loop for(int j = 0; j < n; j++) { //next index to exchange nowIndex = (nowIndex + k) % n; //exchange stmp = nums[nowIndex]; nums[nowIndex] = tmp; tmp = stmp; //finish a circle,move to another circle if(nowIndex == i) { nowIndex = ++i; tmp = nums[nowIndex]; } } }
};


Thanks a lot for the explanation! But could you tell me, how many "loops" can be in an array? Or,to put it another way, what is the maximum value of the variable i? And how does this value depend on the length of an array and on the value of k? For example,I see,that when k is even there are 2 loops, when odd  1.Is there any particular rule?
