(Leetcode) 旋转数组 - Python实现

本文探讨了在给定数组中将元素向右移动k个位置的问题,提供了三种不同的算法实现,包括切片拼接法、循环删除插入法及利用数学符号%的巧妙方法,并分析了各自的优缺点。

题目:旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

示例 :
输入: [1,2,3,4,5,6,7] 和 k = 3,输出: [5,6,7,1,2,3,4]
输入: [-1,-100,3,99] 和 k = 2,输出: [3,99,-1,-100]

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

---------------------------------------------------------------------------

解法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.
        """

        # 切片拼接的方式, 空间复杂度高
        l = len(nums)
        nums[:] = nums[l-k:] + nums[:l-k]

解法2:每次循环在list尾部删除一个,同时在头部加入一个。

注意:pop()方法可以接收被删除的元素。

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

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.
        """
        for i in range(k):
            last = nums.pop()
            nums.insert(0, last)

解法3:巧妙的使用数学符号 %。 

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

参考:

https://www.runoob.com/python/att-list-pop.html

https://blog.youkuaiyun.com/huhehaotechangsha/article/details/80467219

https://blog.youkuaiyun.com/qq_36190978/article/details/86757046

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值