问题描述:
给定一个数组,将数组中的元素向右移动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]
说明:
- 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
- 要求使用空间复杂度为
O(1)
的原地算法。
问题分析:
这个题目如果用Python
的话,应该很简单就可以得出结果,但是这样会失去了题目的意义了哈。此外要注意的是,是在原数组上操作,即,要求使用空间复杂度为 O(1)
的原地算法。下面总结几种常用的方法。
Python3实现:
方法1:使用Python
切片操作,切开,颠倒,组合,完成。
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.
"""
n = len(nums)
nums[:] = nums[n-k:]+nums[:n-k]
方法2:和方法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.
"""
k = k % len(nums)
nums[:k], nums[k:] = nums[len(nums)-k:], nums[:len(nums)-k]
方法3:把这个 nums
翻转, 然后再把对应的两个小区间翻转。(这方法也可以用Python
中的nums[::-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.
"""
def reverse(nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start, end = start + 1, end - 1
n = len(nums)
k = k % len(nums)
reverse(nums, 0, n - 1)
reverse(nums, 0, k - 1)
reverse(nums, k, n - 1)
声明: 总结学习,有问题可以批评指正,大神可以略过哦。
题目链接:leetcode-cn.com/problems/rotate-array/description/