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.