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.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
三种方法
class Solution(object):
#方法一:左边翻转,右边翻转,最后一起翻转
#这个想法很牛逼诶
def reverse(self,nums,low,high):
while low < high:
nums[low],nums[high - 1] = nums[high - 1],nums[low]
low += 1
high -= 1
def rotate(self, nums, k):
n = len(nums)
k = k % n
self.reverse(nums,0,n-k)
self.reverse(nums,n-k,n)
self.reverse(nums,0,n)
#方法2: 直接利用两端拼接
'''
n = len(nums)
k = k%n
nums[:] = nums[n-k:] + nums[:n-k]
'''
#方法三:数组变为原来的二倍,然后取中间的
'''
if k == 0 or nums == []:
return
k = k % len(nums)
l = len(nums)
res = nums[:]
res = res + res
for i in xrange(l):
nums[i] = res[i+l-k]
'''
s = Solution()
nums = [1,2]
k = 1
s.rotate(nums,k)
print nums