Python3解leetcode Rotate Array

问题描述:

 

Given an array, rotate the array to the right by k steps, where k is non-negative.

 

Example 1:

 

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

 

Example 2:

 

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

 

Note:

 

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

 

思路:

解题思路比较多,最关键的想出尽可能多的解题方法

代码

 

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        while k >= len(nums):
            k -=  len(nums)  
        if k == 0:
            return
        num1 = list([int])
        num1[:] = nums[:]
        nums[0:k] = num1[-k:]#利用num的后k个数字,替换nums的前k个数字
        nums[k:] = num1[0:len(num1)-k]
        nums[:] = nums[0:len(num1)]

 

以上代码,时间复杂度为O(1)

Runtime:  48 ms, faster than 94.32% of Python3 online submissions forRotate Array.
Memory Usage:  13.7 MB, less than 5.23% of Python3 online submissions for Rotate Array.
 
 
将代码优化:
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        k = k % len(nums)
        nums[:] = nums[-k:] +  nums[:-k]

以上代码:

Runtime:  48 ms, faster than 94.32% of Python3 online submissions forRotate Array.
Memory Usage:  13.5 MB, less than 32.26% of Python3 online submissions for Rotate Array.
 
以上两组代码相比,运算时间上没有太大的变化;第二个代码少用一个数组的空间,导致空间占用会比较少一些
 
 
 
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        while k >= len(nums):
            k -=  len(nums)  
        if k == 0:
            return
        for i in range(k):
            nums.insert(0,nums[-1])
            nums.pop()

以上代码,时间复杂度O(n)

Runtime:  124 ms, faster than 16.90% of Python3 online submissions forRotate Array.
Memory Usage:  13.4 MB, less than 58.82% of Python3 online submissions for Rotate Array.

 

转载于:https://www.cnblogs.com/xiaohua92/p/11112162.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值