Python 3.x Leetcode二和Python解决方案在我提交Leetcode时不起作用,但在其他编译器上起作用
我刚刚开始使用leetcode,我不知道我是否错了,或者leetcode中是否有一些bug 这是我在Leetcode上键入的代码,用于解决两个求和问题,但它不起作用Python 3.x Leetcode二和Python解决方案在我提交Leetcode时不起作用,但在其他编译器上起作用,python-3.x,Python 3.x,我刚刚开始使用leetcode,我不知道我是否错了,或者leetcode中是否有一些bug 这是我在Leetcode上键入的代码,用于解决两个求和问题,但它不起作用 class Solution: def twoSum(self, nums, target): i=0 j=0 for k in nums: for l in nums: if i!=j:
class Solution:
def twoSum(self, nums, target):
i=0
j=0
for k in nums:
for l in nums:
if i!=j:
if (nums[i]+nums[j])==target:
return [i,j]
j+=1
j=0
i+=1
这是我在Programiz在线编译器上输入的代码,它可以正常工作
class Solution:
def twoSum(self, nums, target):
i=0
j=0
for k in nums:
for l in nums:
if i!=j:
if (nums[i]+nums[j])==target:
return [i,j]
j+=1
j=0
i+=1
testCase=[3,2,4]
target=6
test=Solution()
print(test.twoSum(testCase,target))
它们都有相同的测试用例,但我的代码在programiz上工作,而不是在Leetcode上工作,即您提到的解决方案 超过时限 虽然代码对于一些小输入运行良好,但它没有达到一个大输入的时间限制, 因为有两个for循环 试试这个
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, v in enumerate(nums):
remaining = target - v
if remaining in dic:
return [dic[remaining], i]
dic[v] = i
leetcode会给你什么错误?你可能太慢了。提交时,我的状态为“超出输出限制”。你说我可能太慢是什么意思?考虑到你的程序,这确实是一个非常奇怪的错误代码。你确定你的某个地方没有零散的
打印语句吗?哦!谢谢你。我删除了用于调试的打印语句,并获得“超过时间限制”的状态是,这意味着您的解决方案太慢。你只需要更聪明地计算最终结果!这就是leetcode的困难所在,通常“显而易见”的解决方案不起作用,存在一个更智能、更快的解决方案。