两数之和
(0001_two_sum)
标签: array, hash_map · 难度: EASY
输入
nums:
2
7
11
15
target:
9
执行过程
Step 1 · array_read
读取 nums[0] = 2(索引 0,值 2)
before
i=0
num=2
map:seen={}
after
高亮: {"objects": ["arr:nums"], "indices": {"arr:nums": [0]}}
💡 遍历数组,一次只看一个元素。
Step 2 · hash_map_get
需要补数 7(因为 2 + 7 = 9),检查哈希表...
before
complement=7
map:seen={}
after
高亮: {"objects": ["map:seen"]}
💡 查哈希表 O(1),看补数是否存在。
Step 3 · hash_map_put
把 2 → 索引 0 记录下来,以后可以快速查找
before
map:seen={"2": 0}
after
map:seen={"2": 0}
高亮: {"objects": ["map:seen"]}
💡 当前没找到答案,先记录以便后续查找。
Step 4 · array_read
读取 nums[1] = 7(索引 1,值 7)
before
i=1
num=7
map:seen={"2": 0}
after
高亮: {"objects": ["arr:nums"], "indices": {"arr:nums": [1]}}
💡 遍历数组,一次只看一个元素。
Step 5 · hash_map_get
需要补数 2(因为 7 + 2 = 9),检查哈希表...
before
complement=2
map:seen={"2": 0}
after
高亮: {"objects": ["map:seen"]}
💡 查哈希表 O(1),看补数是否存在。
Step 6 · answer_found
找到了!补数 2 在索引 0,加上当前索引 1 → [0, 1]
before
after
result=[0, 1]
高亮: {"objects": ["map:seen"], "indices": {}}
🧠 哈希表像一本快速查找的字典,key 是见过的值,value 是它的位置。