Posted on

Description

Submission

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();

        vector<int>  new_nums(n);

        k %= n;
        int j = 0;
        for(int i = n - k; i < n; ++i, ++j) {
            new_nums[j] = nums[i];
        }

        for(int i = 0; j < n; ++j, ++i) {
            new_nums[j] = nums[i];
        }

        for(int i = 0; i < n; ++i) {
            nums[i] = new_nums[i];
        }
        
    }
};
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        k %= n;

        int count = gcd(k, n);
        int times = n / count;

        for(int i = 0; i < count; ++i) {
            int cur = i;
            int prev = nums[i];

            for(int t = 0; t < times; ++t) {
                cur = (cur + k) % n;
                swap(nums[cur], prev);
            }
        }
    }
};
//  5 6 7 1 2 3 4
// [1,2,3,4,5,6,7]

Leave a Reply

Your email address will not be published. Required fields are marked *