[leetcode_189]Rotate Array

Rotate an array based on input k. Note that k can be negative or greater than the array length, so take the modulus first. Then output the doubled array starting at offset size-k.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if (nums.size() <= 0)
        {
            return ;
        }
        k %= nums.size();
        vector<int> dNums(nums.size() * 2);
        for (int i = 0;i < nums.size() * 2; i++)
        {
            dNums[i] = nums[i % nums.size()];
        }
        for (int i = 0;i < nums.size(); i++)
        {
            nums[i] = dNums[i + nums.size() - k];
        }
    }
};