Skip to content

Latest commit

 

History

History
67 lines (54 loc) · 1.53 KB

File metadata and controls

67 lines (54 loc) · 1.53 KB

189. Rotate Array

难度: Easy

原题连接

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

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

思路 1

- 空间复杂度: O(k)

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)
        if k != 0:
            tmp = nums[-k:]
            for j in range(len(nums)-1, k-1, -1):
                nums[j] = nums[j-k]
            nums[:k] = tmp

思路 2

- 空间复杂度: O(1)

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]

思路 3

- 空间复杂度: O(1)

还有最容易想到的方法:

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.
        """
        i = 1
        k %= len(nums)
        while i <= k :
            i += 1
            a = nums.pop()
            nums.insert(0, a)