LC练习 旋转数组

博客探讨了三种不同的方法来实现LeetCode中数组旋转的问题,包括直接赋值、环状结构遍历以及反转策略。文章指出,某些方法在LeetCode环境中可能表现不一致,但在外部运行时能得到正确结果。这是一篇关于算法优化和数组操作的编程实践分享。
摘要由CSDN通过智能技术生成

LC练习 旋转数组

LC

1

每次旋转一步,重复k次。可行,但是速度太慢了。

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        
        length = len(nums)
        for i in range(k):
            a = nums[-1]
            for j in range(length-1):
                nums[-j-1] = nums[-j-2]
            nums[0] = a

2

环状结构,遍历所有元素一遍

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        
        length = len(nums)
        k = k % length
        count = 0 #用于记录移动次数
        start = 0
        while count < length: #所有元素都移动一次结束
            current = start
            prev = nums[current]
            while True:
                later = (current + k) % length
                tem = nums[later]
                nums[later] = prev 
                prev = tem
                current = later
                count += 1
                if start == current:
                    break
            start += 1

3

反转

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        k = k % length
        nums.reverse()
        nums[:k] =[i for i in reversed(nums[:k])] 
        nums[k:] =[i for i in reversed(nums[k:])] 

这里有一个问题,不知道为什么这样写在LC里不对,但是外面跑,print()是对的?

nums = list(reversed(nums))
nums[:k] = list(reversed(nums[:k]))
nums[k:] = list(reversed(nums[k:]))
print(nums)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值