题目:
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
分析:
- 将右侧元素旋转k次至左端
- 当k=0时,数组无需旋转
- 当k=n时,数组无需旋转
- 当k>n时,相当于在3的基础上再旋转k-n次
- 统一以上思路,对数组进行k=k%n次旋转操作
代码:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) > 1:
k = k % len(nums)
if k != 0:
nums[:k - 1],nums[k:] = nums[- k:],nums[:-k]
思考:
- 该代码在leetcode中优于88.9%的case