旋转数组(python实现)

问题:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(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.
        """
        long = len(nums)
        newk= k % long
        temp = []
        for i in range(long):
            temp.append(nums[i-newk])
        for j in range(long):
            nums[j] = temp[j]

解题思路
数组无论怎样移动,元素之间的顺序是不会变得,只要找到最后的状态即可;
使用一个空数组 temp = [] 保存 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.
        """
        if k == 0 or len(nums) == 0:
            return
        k = k % len(nums)
        nums[:] = nums[len(nums)-k:]+nums[:len(nums)-k]

解题思路:
nums依照k进行分片,然后进行合并

猜你喜欢

转载自blog.csdn.net/WJ7594/article/details/82931167