Single-loop in-place rotation


  • 0
    L

    8ms C code. O(n) time with a single for-loop. Rotated in place.

    void rotate(int* nums, int numsSize, int k) {
        k %= numsSize;
        int startIndex = 0;
        int replacedInt = nums[0];
        int startedHere = 0;
        for (int i = 0; i < numsSize; i++) {
            int wasReplaced = replacedInt;
            startIndex = (startIndex+k)%numsSize;
            replacedInt = nums[startIndex];
            nums[startIndex] = wasReplaced;
            if (startIndex == startedHere) {
                startedHere = ++startIndex;
                replacedInt = nums[startIndex];
            }
        }
    }

Log in to reply
 

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