#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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].
'''
class Solution(object):
def __rotate(self,nums,left,right):
while left < right:
tmp = nums[left]
nums[left] = nums[right]
nums[right] = tmp
left += 1
right -= 1
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if 0 == length or 0 == k % length:
return
k = k % length
self.__rotate(nums,0,length - k - 1)
self.__rotate(nums,length - k,length - 1)
self.__rotate(nums,0,length - 1)
if __name__ == "__main__":
s = Solution()
l = range(1,8)
s.rotate(l,2)
print l
44 leetcode - Rotate Array
最新推荐文章于 2025-08-08 00:00:33 发布