Leetcode 中双和问题的算法没有输出

No output from algorithm for Two Sum problem in Leetcode

我编写的旨在解决二和问题的代码:

def twoSum(self, nums: List[int], target: int) -> List[int]:
   
    dict = {}

    for i in range(len(nums)):
        complement = target - nums[i]
        if complement in dict:
            return [dict[complement], i]
        dict[complement] = i

我刚开始在 LeetCode 上练习,我在解决两个和问题时遇到了问题。

问题陈述:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

我的推理是创建一个字典并遍历数字,并为每个数字生成一个补数,然后我在我的字典中查找,如果它确实存在,那么我 return生成该补码的索引和当前索引 i。否则,我插入带有补码的密钥。

不知怎么的,我的函数没有输出任何东西,只有两个空括号。下面是示例输入和正确的输出。

Input: nums = [3,2,4], target = 6
Output: [1,2]

最后一行错了。它应该显示为 dict[nums[i]] = i,因为您正在为它们的值存储索引。这是具有更好的变量名且不影响内置类型的整个函数:

def twoSum(self, nums, target):
    dct = {}
    for i in range(len(nums)):
        complement = target - nums[i]
        if complement in dct:
            return [dct[complement], i]
        dct[nums[i]] = i

或者更简洁地使用 enumerate 并存储其补充值的索引:

def twoSum(self, nums, target):
    dct = {}
    for i, num in enumerate(nums):
        if num in dct:
            return [dct[num], i]
        dct[target - num] = i

您可能会注意到您混合使用了这两种方法。你在 dct 中寻找补码,也想存储它作为当前索引。两者之一需要是当前值。