LeetCode:189. Rotate Array - Python

问题描述:

189. 旋转数组

给定一个数组,将数组中的元素向移动k个位置,其中k是非负数。

示例 1:

输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释: 向右旋转 1 步: [7,1,2,3,4,5,6],向右旋转 2 步: [6,7,1,2,3,4,5],向右旋转 3 步: [5,6,7,1,2,3,4]

说明:

  • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
  • 要求使用空间复杂度为 O(1)的原地算法。

问题分析:

这个题目如果用Python的话,应该很简单就可以得出结果,但是这样会失去了题目的意义了哈。此外要注意的是,是在原数组上操作,即,要求使用空间复杂度为 O(1)的原地算法。下面总结几种常用的方法。

Python3实现:

方法1:使用Python切片操作,切开,颠倒,组合,完成。

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.
        """
        n = len(nums)
        nums[:] = nums[n-k:]+nums[:n-k]

方法2:和方法1类似。

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.
        """
        k = k % len(nums)
        nums[:k], nums[k:] = nums[len(nums)-k:], nums[:len(nums)-k]

方法3:把这个 nums翻转, 然后再把对应的两个小区间翻转。(这方法也可以用Python中的nums[::-1]实现)

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.
        """
        def reverse(nums, start, end):
            while start < end:
                nums[start], nums[end] = nums[end], nums[start]
                start, end = start + 1, end - 1

        n = len(nums)
        k = k % len(nums)
        reverse(nums, 0, n - 1)
        reverse(nums, 0, k - 1)
        reverse(nums, k, n - 1)

声明: 总结学习,有问题可以批评指正,大神可以略过哦。
题目链接:leetcode-cn.com/problems/rotate-array/description/

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/82905287
今日推荐