My C in-place solution,O(1) space, O(n) time


  • 1
    A
    void rotate(int* nums, int numsSize, int k) {
        k%=numsSize;
        if(k) {
            int cur,last,i,j,index;
            int gcd=numsSize,b=k;
            while(b) {
                i=gcd;
                gcd=b;
                b=i%b;
            }
            b=numsSize/gcd;
            for(i=0;i<gcd;++i)
                for(j=b,index=i,last=nums[i+numsSize-k];j>0;--j) {
                    cur=nums[index];
                    nums[index]=last;
                    index+=k;
                    if(index>=numsSize)index-=numsSize;
                    last=cur;
                }
        }
    }

Log in to reply
 

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