[LeetCode]189. Rotate Array
1、题目描述
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.
2、解题思路
1)k把数组分割为两部分元素,原地移动多的部分,借助一个临时数组把少的那部分暂存,然后再填到空出来的位置。注意k大于数组长度的情况,要取余。
2)先整体做一次旋转,然后再分别旋转分割的两部分。k要取余。
3)也可以两部分先分别旋转,再整体旋转。
4)创建tail元素,把数组的收尾连接起来,然后进行旋转。
第2/3种简单有效。第1种只能说是勉强完成。第4种也比较简单易懂O(n^2)。
尝试:尝试双指针的思路