数组-LeetCode189-Rotate Array

第一种方法不占用额外空间,但是时间复杂度比较高

class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """

        for i in range(k):
        for j in range(len(nums)-1):
        nums[len(nums)-1],nums[j]=nums[j],nums[len(nums)-1]
 第二种方法会用,不是很懂原理,有一个疑问就是最后面为什么是nums[:],为什么不是nums?     

class Solution:
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """

        i = k%len(nums)
        nums[:]= nums[-i:]+nums[:-i]

猜你喜欢

转载自blog.csdn.net/sjzuliguoku/article/details/81515435
今日推荐