44 leetcode - Rotate Array

来源:互联网 发布:微商城数据统计 编辑:程序博客网 时间:2024/06/05 22:36
#!/usr/bin/python# -*- coding: utf-8 -*-'''Rotate ArrayRotate 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
0 0