问题描述:
Rotate an array of n elements to the right by k steps.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
示例:
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]
.
思路分析:
这道题还是很常见的吧,只需要旋转三次就行了。但是,这道题有一个问题需要考虑到:如果k大于数组长度咋办?也就是说上面的例子可以旋转3次,也可以旋转10次等等,以此类推,所以我们在这要来一个求余操作,即 k %= n.
代码: