Leetcode 189:旋转数组(最详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/83791839

给定一个数组,将数组中的元素向右移动 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]

示例 2:

输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

说明:

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

解题思路

类似问题

Leetcode 61:旋转链表(最详细解决方案!!!)

右旋k步,相当于左旋nums_len - k%nums_len(和上面问题一样的处理)。例如

1 2 3 4 5 6 7

左旋一步,对于原来是7的位置来说现在变成了1,相当于位置6的元素变成了位置(6+k)%nums_len=0的元素。代码如下

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.
        """
        nums_len = len(nums)
        k = nums_len - k%nums_len
        result = nums[:]
        for i in range(nums_len):
            nums[i] = result[(i+k)%nums_len]

或者直接向右旋转也可以,转换的过程思路同上,只不过位置换了一下。

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.
        """
        nums_len = len(nums)
        result = nums[:]
        for i in range(nums_len):
            nums[(i+k)%nums_len] = result[i]

一个更pythonic的写法。

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

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/83791839