gpt4 book ai didi

python - Leetcode 在无可争议的正确答案时声称错误答案

转载 作者:行者123 更新时间:2023-12-01 22:47:20 25 4
gpt4 key购买 nike

我正在尝试完成 Leetcode 上的 189. 旋转数组问题。这是我写的代码:

class Solution(object):
def rotate(self, nums, k):
end = len(nums) - 1
carry = []
new = [n for n in nums]
for i in range(end-k+1, end+1):
carry.append(nums[i])
for i in range(1, k+1):
new.pop()
for n in new:
carry.append(n)
print(carry)
return carry

(过时的变量是为了尝试消除 Leetcode 测试系统发生古怪事件的任何可能性。)

我可以在任何地方运行此代码(我已经尝试过 VS Code 和在线解释器)并且结果总是正确的(对于第一种情况,[5, 6, 7, 1, 2, 3, 4])。但是,当我在 Leetcode 中尝试时:

Leetcode message

stdout 在返回之前的行中按字面意思显示正确答案,但数组在未被篡改的情况下以某种方式神奇地发生了变化。

这让我难以自拔……请帮忙!!

(问题描述:

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]


Constraints:

1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105


Follow up:

Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
Could you do it in-place with O(1) extra space?

)

最佳答案

this problem 的 Python 模板说:

class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""

如文档字符串所述,您需要就地修改 nums。无需打印或返回任何东西。

对现有代码的一个简单修复是在末尾使用赋值 nums[:] = carry

关于python - Leetcode 在无可争议的正确答案时声称错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75025075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com