假设我们有一个数组A。我们必须向右旋转k步。因此,如果数组为A = [5、7、3、6、8、1、5、4],并且k = 3,则输出将为[1,5,4,5,7,3,6, 8]。步骤就像
[4,5,7,3,6,8,1,5]
[5,4,5,7,3,6,8,1]
[1,5,4,5,7,3,6,8]
为了解决这个问题,我们将按照以下步骤进行。
令n为数组的大小
k = k mod n
A =从n – k到end的A子数组+从0到n – k – 1的A子数组
让我们看下面的实现以更好地理解-
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%=n nums[:] = nums[n-k:]+nums[:n-k] nums = [5,7,3,6,8,1,5,4] ob1 = Solution()ob1.rotate(nums, 3) print(nums)
nums = [5,7,3,6,8,1,5,4] k = 3
输出结果
[1,5,4,5,7,3,6,8]