数组旋转 Leetcode#189
Posted
技术标签:
【中文标题】数组旋转 Leetcode#189【英文标题】:Array Rotation Leetcode#189 【发布时间】:2022-01-18 15:52:40 【问题描述】:在 Leetcode 的数组轮换问题中,为什么他们只使用 k %= len(nums)?
def rotate(nums, k):
k %= len(nums)
for i in range(k):
previous = nums[-1]
for j in range(len(nums)):
nums[j], previous = previous, nums[j]
return nums
【问题讨论】:
【参考方案1】:如果您将数组旋转n
其中n == len(array)
您实际上是在创建相同的数组,如下所示:
arr = [1,2,3]
k = 3
1. [3,1,2]
2. [2,3,1]
3. [1,2,3] # as you can see, this array is the same as the original
这意味着我们可以避免多余的旋转,只旋转k % len(arr)
。
例子:
arr = [1,2,3]
k = 5
1. [3,1,2]
2. [2,3,1]
3. [1,2,3] # this equals the original
4. [3,1,2] # this equals step 1
5. [2,3,1] # this equals step 2
# Since 5 % len(arr) = 5 % 3 = 2
# and since step 5 is the same as step 2
# we can avoid the redundant repetition
# and go for k % len(arr) = 2 from the start
【讨论】:
以上是关于数组旋转 Leetcode#189的主要内容,如果未能解决你的问题,请参考以下文章