通过反转部分反转列表不会更新列表
Reversing lists partially by reversing does not update the list
我正在尝试解决以下问题:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]
我试图通过反转列表来解决这个问题,然后反转列表的第一个 k
元素,然后反转列表的其余部分。像这样:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums = nums[::-1]
print('1st reverse', nums)
nums[:k] = nums[:k][::-1]
print('2nd reverse', nums)
nums[k:] = nums[k:][::-1]
print('final reverse', nums)
但这是我的输出。列表 nums
保持不变:
Your input
[1,2,3,4,5,6,7]
3
stdout
1st reverse [7, 6, 5, 4, 3, 2, 1]
2nd reverse [5, 6, 7, 4, 3, 2, 1]
final reverse [5, 6, 7, 1, 2, 3, 4]
Output
[1,2,3,4,5,6,7]
Expected
[5,6,7,1,2,3,4]
尽管 nums
是我最终反转中的正确顺序。我哪里错了?
这个:
nums = nums[::-1]
将 nums
分配给新列表。您随后对 nums
执行的所有操作都 而不是您最初传递给函数的列表中的 。
您正在寻找:
nums[:] = nums[::-1]
我正在尝试解决以下问题:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]
我试图通过反转列表来解决这个问题,然后反转列表的第一个 k
元素,然后反转列表的其余部分。像这样:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums = nums[::-1]
print('1st reverse', nums)
nums[:k] = nums[:k][::-1]
print('2nd reverse', nums)
nums[k:] = nums[k:][::-1]
print('final reverse', nums)
但这是我的输出。列表 nums
保持不变:
Your input
[1,2,3,4,5,6,7]
3
stdout
1st reverse [7, 6, 5, 4, 3, 2, 1]
2nd reverse [5, 6, 7, 4, 3, 2, 1]
final reverse [5, 6, 7, 1, 2, 3, 4]
Output
[1,2,3,4,5,6,7]
Expected
[5,6,7,1,2,3,4]
尽管 nums
是我最终反转中的正确顺序。我哪里错了?
这个:
nums = nums[::-1]
将 nums
分配给新列表。您随后对 nums
执行的所有操作都 而不是您最初传递给函数的列表中的 。
您正在寻找:
nums[:] = nums[::-1]