给定一个数组,将数组中的元素向右移动 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) 的 原地 算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
n=len(nums)
k=k%n
nums[:]=nums[n-k:]+nums[:n-k]
return nums
执行结果:
通过
显示详情
执行用时:28 ms, 在所有 Python 提交中击败了46.16%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了25.00%的用户
思路2
三次翻转,第一次对前半段翻转,第二次对后半段翻转,第三次对总列表翻转
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
n=len(nums)
k=k%n
nums[:]=(nums[:n-k][::-1]+nums[n-k:][::-1])[::-1]
return nums
执行结果:
通过
显示详情
执行用时:24 ms, 在所有 Python 提交中击败了65.93%的用户
内存消耗:13.1 MB, 在所有 Python 提交中击败了25.00%的用户
思路3
插入法
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
for i in range(k):
nums.insert(0,nums.pop())
return nums
执行结果:
通过
显示详情
执行用时:120 ms, 在所有 Python 提交中击败了8.38%的用户
内存消耗:13.5 MB, 在所有 Python 提交中击败了25.00%的用户