在 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
uj5u.com熱心網友回復:
如果您按照以下方式有效地創建相同陣列的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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387611.html
