Python3解leetcode Rotate Array
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python3解leetcode Rotate Array,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1657字,纯文字阅读大概需要3分钟。
内容图文
![Python3解leetcode Rotate Array](/upload/InfoBanner/zyjiaocheng/782/9cfa1d6c10fc44d7b06434475a938f0e.jpg)
问题描述:
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. """ 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.
内容总结
以上是互联网集市为您收集整理的Python3解leetcode Rotate Array全部内容,希望文章能够帮你解决Python3解leetcode Rotate Array所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。