You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Two Sum代码里nums_dict[complement]的含义是什么?

Two Sum代码中nums_dict[complement]的含义解析

问题背景

我正在解决Two Sum问题,问题描述为:给定整数数组nums和整数target,返回两个数的索引,使得它们相加等于target。可假设每个输入恰好有一个解,且不能重复使用同一元素,返回顺序不限。例如输入nums = [2,7,11,15]、target = 9时,输出应为[0,1]。

我理解代码整体流程,但无法理解代码行return [nums_dict[complement],i]中nums_dict[complement]的含义,想确认这是获取字典的索引还是对应的值,我的代码如下:

class Solution(object):
    def twoSum(self,nums,target):
        nums_dict = {}
        for i,num in enumerate(nums):
            complement = target-num
            if complement in nums_dict:
                return [nums_dict[complement],i]  # are we getting index or value of the dictionary
            else:
                nums_dict[num]=i
        return []

if __name__ == '__main__':
    arr = [2,7,11,15],  # 这里多了逗号,会导致arr成为元组,需要去掉
    target =9
    print(Solution().twoSum(arr,target))

核心疑问解答

首先明确nums_dict的存储逻辑:代码中nums_dict[num] = i这一行,是把数组中的数值num作为字典的键(key),把该数值对应的数组索引i作为字典的值(value)。

所以:

  • complement in nums_dict是检查complement这个数值是否已经作为键存在于字典中;
  • nums_dict[complement]是通过键complement获取对应的索引值——也就是之前遍历到的、数值等于complement的元素在数组中的位置。

用你的测试用例举例:

  1. 第一次循环:i=0,num=2,complement=7,此时字典为空,执行nums_dict[2] = 0,字典变为{2: 0};
  2. 第二次循环:i=1,num=7,complement=2,此时2是字典的键,nums_dict[2]取到值0,返回[0,1],正好是正确的索引对。

小提示

你的测试代码里arr = [2,7,11,15],多了一个逗号,会让arr变成元组类型,传入twoSum方法时会触发错误,需要去掉这个逗号。

内容的提问来源于stack exchange,提问作者PurpleRabbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:23:09