Skip to content

189 rotate array

189. Rotate Array

题目: https://leetcode.com/problems/rotate-array/

难度 : Easy

首先,要知道一点,k如果大于nums的长度了,那么其实进行 k % len(nums) 次就行了

其次,要注意k 为0的情况

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        k = k % len(nums)
        if k != 0:
            tmp = nums[-k:]
            for j in range(len(nums)-1, k-1, -1):
                nums[j] = nums[j-k]
            nums[:k] = tmp

还有作弊大法,贼🐂批

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

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组