Answer I get, but I can not understand it well

  • 0

    class Solution {

        void rotate(int nums[], int n, int k) {
            int count = 0;
            int current  = 0;
            int vcurrent = nums[current];
            int ocurrent = current;
            while(count < n){
                std::swap(vcurrent, nums[(current + k) % n]);
                current = (current + k) % n;
                if(current == ocurrent){
                    current = (ocurrent + 1) % n;
                    vcurrent = nums[current];
                    ocurrent = current;


    every time put one element to its proper place, and use vcurrent to keep the old one
    do it for n times.

    but if the current return to its original value before n exchanges, let's start from a new index.

    I get this solution but even I couldn't understand it intuitively.
    Any comments are welcome.

  • 0

    I have got the answer, every time the indices forms an arithmetic seq. with common different k.
    if xk repeats, start from start + 1

    when k == 1 xk will definitely repeat, however we have count < n constraint, so it's ok.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.