## # 189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

``````Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
``````

Example 2:

``````Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
``````

Note:

• Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
• Could you do it in-place with O(1) extra space?

### # Solution

Approach 1: Using extra array.

Approach 2: Using cyclic replacement.

Approach 3: Using reverse.

### # Code (Python)

Approach 1:

Approach 2:

``````    def rotate(self, array, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k = k % len(array)
if k == 0 or len(array) == 1:
return
num_switches = 0
beginning = 0
index = 0
number = array[index]
while True:
new_index = (index + k) % len(array)
new_number = array[new_index]
array[new_index] = number
#print array
num_switches += 1
index = new_index
number = new_number

if index == beginning:
beginning += 1
index = beginning
number = array[index]

if num_switches == len(array):
break
``````

Approach 3:

### # Code (C++)

Approach 1:

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

Approach 2:

``````class Solution {
public:
void rotate(vector<int>& nums, int k) {
int numsSize = nums.size();
int count = 0;
for (int start = 0; count < numsSize; ++start)
{
int curr = start;
int prevNum = nums[start];
do
{
curr = (curr + k) % numsSize;
int tmp = nums[curr];
nums[curr] = prevNum;
prevNum = tmp;
count++;
} while (curr != start);
}
}
};
``````

Approach 3:

``````class Solution {
public:
void rotate(vector<int>& nums, int k) {
int numsSize = nums.size();
if (numsSize == 0) return;
int realK = k % numsSize;
reverse(nums, 0, numsSize - 1);
reverse(nums, 0, realK - 1);
reverse(nums, realK, numsSize - 1);
}
private:
void reverse(vector<int>& nums, int head, int tail) {