O(1) space inplace rotate C code


  • 1
    K

    it takes less operation than 3 rotate method, by it's harder to code, a lot of gotchas, took a while to debug..

    void rotate(int nums[], int n, int k) {
        k = k%n; if (k==0) return;
        int pos = n-k, i = 0, last = nums[pos], temp, m = 1, j = n-1;
        while (1) {
            temp = nums[i];
            nums[i] = last;
            last = temp;
            if (j--==0) break;
            else {
                if (i < pos) i += k;
                else if (i > pos) i -= n-k;
                else {i = m++; last=nums[++pos];}
            }
        }
    }

Log in to reply
 

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