189. 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.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
大意
旋转数组
答案
1 | class Solution { |
思路
很简单的一道题,但是毕竟第一次见。
三步反转法来做,时间复杂度是O(n),空间复杂度是O(1)
一共有3步。假设输入数组的下标是0~ n-1,需要rotate的步数是k.
step 1 reverse原来的数组
step 2 reverse 0~ k-1
step 3 reverse k ~ n-1
Author: corn1ng
Link: https://corn1ng.github.io/2017/12/04/算法/leetcode189/
License: 知识共享署名-非商业性使用 4.0 国际许可协议