Think of the array as a ring. My Java solution.


  • 0
    M

    Think of the array as a ring. and move each element in turn.

    if (nums == null || k <= 0 || k == nums.length) {
                return;
            }
    
            if (nums.length == 1) {
                return;
            }
    
            if (k > nums.length) {
                k = k % nums.length; // several circles
            }
    
            int i = 0, p = 0, global = nums[0], q = 0;
            while (i < nums.length) {
                int nextPos = p + k;
                if (nextPos > nums.length - 1) {
                    nextPos = nextPos % nums.length;
                }
                int temp = nums[nextPos];
                nums[nextPos] = global;
                if (nextPos == q) {
                    p = q + 1;
                    global = nums[p];
                    ++q;
                } else {
                    global = temp;
                    p = p + k;
                }
                i++;
            }
    

Log in to reply
 

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