C++, O(1) Space, only n times of assignments


  • 1
    void rotate(vector<int>& nums, int k) {
        int i = 0, start = 0, n=nums.size();
        k %= n;
        while (i<n) {
            int c = 0, j = start, t1 = nums[j];
            while (j!=start || c==0) {
                int ind = (j+k)%n;
                int t2 = nums[ind];
                nums[ind] = t1;
                t1 = t2;
                j = ind;
                i++;
                c++;
            }
            start++;
        }
    }

Log in to reply
 

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