LeetCode 189. 旋转数组 Rotate Array
Table of Contents
中文版:
给定一个数组,将数组中的元素向右移动 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]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。
英文版:
Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space?
My answer:
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) k = k % n # 上一步是为了 Corner case: [1,2,3,4,5,6] k = 11 的情况 self.helper(nums,0, n-k-1) self.helper(nums,n-k,n-1) self.helper(nums,0,n-1) def helper(self,nums,start,end): while start < end: temp = nums[start] nums[start] = nums[end] nums[end] = temp start += 1 end -= 1 # print(nums) """ 知识点: 1、nums[0:n-k-1] 截取 list 片段是新生成一个 list,不改变原来的list """
解题报告:
例子:[1,2,3,4,5,6,7] k = 3
三步翻转法:
1、翻转 0 到 n-k-1: 4321 567
2、翻转 n-k 到 n-1: 4321 765
3、翻转 0 到 n-1: 5671234
此方法同样适用于翻转字符串题目。