189. 数组旋转 Rotate Array
2016-03-08 本文已影响89人
BeijingIamback
Rotate an array of n elements to the right by k steps.
把后边K个元素旋转到前边。
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].
代码:

解题思路:【1, 2, 3, 4, 5, 6,7】 k=3
首先旋转前n-k=4个元素 【4,3,2,1,5,6,7】
在旋转后k个元素【4,3,2,1,7,6,5】
最后把整个数组旋转,【5,6,7,1,2,3,4】。
注意k的取值要是大于n,需要对k取余数。