标签:ext pac ble type mod code 例子 一个 超出
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
给出一个数组和k,让你把数组往右移动k部,超出数组的部分移动到数组的头部,实际上有很多种解法。
如果要求O1的额外空间的话,做法就有点有意思了。
可以两段先反转,然后再整体反转,举个例子,[1,2,3,4,5,6,7] k= 3 -> [4,3,2,1] [7,6,5] ->[5,6,7,1,2,3,4]
神奇吧
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 for i in range(0, (n - k + 1) // 2, 1): nums[i], nums[n - k - i - 1] = nums[n - k - i - 1], nums[i] for i in range(0, (k + 1) // 2, 1): nums[n - k + i], nums[n - i - 1] = nums[n - i - 1], nums[n - k + i] for i in range(0, n // 2, 1): nums[i], nums[n - i - 1] = nums[n - i - 1], nums[i]
[1,2,3,4,5,6,7], k = 3
标签:ext pac ble type mod code 例子 一个 超出
原文地址:https://www.cnblogs.com/whatyouthink/p/13308424.html