Leetcode.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) 的原地算法。

思路:

使用insert和pop方法,每次将末位的值插到数组最前后直接删除末位值。此算法为原地算法且可以适应k大于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 nums==[]:
            return []
        n=len(nums)-1
        for i in range(0,k):
            nums.insert(0,nums[n])
            nums.pop()

分析:
时间复杂度O(N),空间复杂度O(1)

猜你喜欢

转载自blog.csdn.net/u013942370/article/details/82355973