旋转数组(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进行分片,然后进行合并

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值