Leedcode(初级算法3):旋转数组

旋转数组

给定一个数组,将数组中的元素向右移动 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) 的原地算法。

代码

先用段python里面的切片方法吧

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        k = k % l
        if l > 1 and k > 0:
            nums[:] = nums[-k:] + nums[:-k]
                    

切片方法真是个好东西啊,跑下下面的两个片段就知道怎么用了:

n = [1, 2, 3, 4, 5]
print(n[-3:])
print(n[-2:])
print(n[:-3])
print(n[:-2])

答案在此:

[3, 4, 5]
[4, 5]
[1, 2]
[1, 2, 3]

先这种方法吧,我再去研究研究有没有其他方法。
ok,现在再贴个很low的刚刚写出来的算法。

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        k = k % l
        temp = []
        temp[:] = nums[:]
        for i in range(0,l):
            if i+k < l:
                nums[i+k] = temp[i]
            else:
                nums[(i+k)%l] = temp[i]
            

笑死了,刚刚又稍微改了下,发现从战胜52%到74%哈哈哈哈哈

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        k = k % l
        temp = nums[:]
        for i in range(0,l):
            if i+k < l:
                nums[i+k] = temp[i]
            else:
                nums[(i+k)%l] = temp[i]
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值