Problem
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
1 |
|
Example 2:
1 |
|
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?
Explanation 1
- We can create a copy of the array
temp
, then iterate the array with a relationship(i+k)%n -> i
.
Solution 1
1 |
|
Explanation 2
-
We can use $O(1)$ space to solve this problem.
-
First, reverse the first (n-k) numbers.
-
Then, reverse the last k numbers.
-
Finally, reverse the whole array.
Solution 2
1 |
|