题目描述
给定一个数组,将数组中的元素向右移动 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]
思想
主要有两种大方向的思路:
1.进行翻转的操作
- 翻转
len-k%len
到len-1
. - 翻转
0
到len-k%len-1
- 翻转
0
到len-1
2.取值拼接
代码1
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.
"""
def rev(start, end, s):
while end > start:
s[start], s[end] = s[end], s[start]
end -= 1
start += 1
length = len(nums)
rev(length-k%length, length-1, nums)
rev(0, length-k%length-1, nums)
rev(0, length-1, nums)
代码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.
"""
l = len(nums)
nums[:] = nums[l-k%l:] + nums[:l-k%l]