# LeetCode Rotate Array

LeetCode Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array `[1,2,3,4,5,6,7]` is rotated to `[5,6,7,1,2,3,4]`.

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Related problem: Reverse Words in a String II

```class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if (n < 2 || k%n == 0)return;
k %= n;
while (k--) {
int last = nums[n - 1];
int j = n - 2;
while (j >= 0) {
nums[j + 1] = nums[j];
--j;
}
nums[0] = last;
}
}
};
```

```class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if (n < 2 || k%n == 0)return;
k %= n;
vector<int> right(nums.begin() + n - k, nums.end());
int i = n - k - 1, j = n - 1;
while (i >= 0) nums[j--] = nums[i--];
i = 0;
while (i < k) {
nums[i] = right[i];
++i;
}
}
};
```

```class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if (n < 2 || k%n == 0)return;
k %= n;
vector<int> right(nums.begin() + n - k, nums.end());
right.reserve(n);
right.insert(right.end(), nums.begin(), nums.begin() + n - k);
nums = right;
}
};
```

```class Solution {
private:
void my_reverse(vector<int>::iterator bg, vector<int>::iterator ed) {
--ed;
while (bg < ed) {
swap(*bg, *ed);
++bg;
--ed;
}
}
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if (n < 2 || k%n == 0)return;
k %= n;
my_reverse(nums.begin(), nums.end());
my_reverse(nums.begin(), nums.begin() + k);
my_reverse(nums.begin() + k, nums.end());
}
};
```