My c++ in place solution(no reverse)


  • 0
    P

    The trick is if we never jump to the start position, we can traverse the whole array. If we jump to the start position, the num in position start+1 must not be visited!

    void rotate(vector<int>& nums, int k) {
        if (nums.empty() || k == 0) return;
        int len = nums.size(), moved = 0, i = 0, t = nums[0], starti = 0;
        while (++moved <= len) {
            i = (i+k) % len;
            swap(t,nums[i]);
            if (i == starti) {
                i = ++starti;
                t = nums[i];   
            }
        }
    }

  • 0
    Z

    Doubt that if nums.size() == 1, then i = ++starti; t = nums[i]; will produce an out-of-bound


  • 0
    P

    Good comment! In fact it just tries to read the value beyond the bound and do nothing, so I think it might not cause any issues(Maybe this explanation is wrong!). But if you do care, use
    i = ++starti % len;


Log in to reply
 

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