arrays - 为什么底部 for 循环不包含最后一个元素?
问题描述
问题:给定一个数组,将数组向右旋转 k 步,其中 k 是非负数。
示例:输入:nums = [1,2,3,4,5,6,7], k = 3 输出:[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.
"""
x = nums
for i in range(0, k):
temp = []
temp += [x.pop()]
for i in range(0, len(x)):
temp += [x[i]]
x = temp
for i in range(0, len(nums)):
nums[i] = x[i]
我只得到 [5,6,7,1,2,3] 的输出,我不知道为什么最后一个元素,即 4 被切掉,即使我在尝试打印 x 时看到它。
信用:这是一个 leetcode 问题
解决方案
我看到您正在尝试通过 x = nums 复制您的 nums,但这不是 python 的工作方式(其他语言可能不同)。您在 x 上应用的任何内容也适用于 nums。由于您使用的是 x.pop(),因此 nums 数组也会不可逆地缩小。为了制作 nums 的副本,您可以使用 nums[:]。我更改了您的代码,现在可以使用。(也在 leetcode 上运行)
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.
"""
x = nums[:]
for i in range(0, k):
temp = []
temp += [x.pop()]
for i in range(0, len(x)):
temp += [x[i]]
x = temp
for i in range(0, len(nums)):
nums[i] = x[i]
推荐阅读
- c# - MediaPlayer 和 RenderTargetBitmap 从视频中获取帧图像的问题
- jsf - 如何使用带有自定义或“无”主题的 PrimeIcons
- visual-studio - docker compose 环境变量中的点符号不起作用
- django - 如何在不克隆数据库关系的情况下克隆模型实例?
- asp.net-mvc - 使用 Microsoft 帐户通过 Azure 进行单点登录
- graph - 如何在 sas 分辨率中增加 kaplan-Meier 生存图
- python - 错误:“不正确的令牌已通过” discord.py
- docker - Docker Swarm + Traefik + Moodle 网关错误
- python - 如何在不使用 Gcloud 命令行的情况下获取 Google OAUTH 令牌
- c# - 如何使用自定义哈希函数检查 C# 字典中是否存在冲突?