旋转数组和链表
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].
题目大意:将数组右旋k步
解法一:
解法1:1.旋转整个数组: [1,2,3,4,5,6,7] => [7,6,5,4,3,2,1]
2.旋转前k个数:[7,6,5,4,3,2,1] => [5,6,7,4,3,2,1]
3.旋转后n-k个数:[5,6,7,4,3,2,1] => [5,6,7,1,2,3,4]
1 | class Solution { |
另外的解法参考:
http://www.cnblogs.com/vincently/p/4299924.html
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
解法,首尾相连,头部向前移动len(List) - k % len(List)步
1 | /** |