NeetCode #36LC-1EasyArrays & HashingBlind 75NC 150NC 250
← Back to All Problems#36 · #1 · Two Sum(两数之和)
📌 Problem Statement & Constraints
Given an array of integers
nums and an integer target, return the indices [i, j] such that nums[i] + nums[j] == target, with i != j. Exactly one solution is guaranteed, and you may not use the same element twice. Constraints: 2 <= nums.length <= 10^4, -10^9 <= nums[i], target <= 10^9.💡 Core Algorithmic Approaches
- The brute-force double loop is O(n^2). The key observation is that once you fix the current element
x, the partner you need is fully determined:target - x. - Keep a hash map from value to index for the elements already visited.
- For each
xat indexi, check whethertarget - xis already in the map. If it is, its stored indexj < iforms a valid answer[j, i]. - Only insert
xafter the lookup. Inserting first would let an element pair with itself when2 * nums[i] == target.
💻 Benchmark Python3 Implementation
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen: # lookup BEFORE insert -> no self-pairing
return [seen[need], i]
seen[x] = i
return [] # unreachable per problem guarantee⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single pass with O(1) average hash lookups and insertions. The O(n^2) brute force is the only realistic alternative.
💾 Space Complexity
O(n) for the hash map. Note that the map stores at most one index per distinct value, so a duplicate value overwrites the earlier index -- which is fine, because the earlier index would already have produced an answer if it could.
⚠️ Interview Pitfalls & Follow-ups
- Inserting before looking up:
nums = [3, 3],target = 6would return[0, 0], reusing one element twice. - Sorting plus two pointers: it finds the values in O(n log n), but you must return original indices, so you would have to carry index-value pairs and handle duplicates carefully.
- Assuming the array is sorted: it is not; the hash map makes order irrelevant.
- Worrying about integer overflow: values reach 1e9, so
target - xcan be about 2e9 -- harmless in Python, but a real concern in Java/C++ with 32-bit ints.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案,且同一个元素不能使用两遍。返回顺序任意。约束:2 ≤ nums.length ≤ 10^4;-10^9 ≤ nums[i] ≤ 10^9;-10^9 ≤ target ≤ 10^9。
核心要点
- 暴力枚举 :双重循环检查所有 (i, j) 对,O(n^2),仅在 n 很小时可接受,是面试时用来引出优化的对照基线。
- 一次遍历哈希表(标准解) :维护 值: 下标 的字典。遍历到下标 i 时,先查 target - nums[i] 是否已在字典中;若在,直接返回 [seen[target - nums[i]], i] ;否则把 nums[i]: i 存入。
- 为什么「先查后存」而不是「先存后查」 :先查后存天然避免了「同一个元素用两遍」的问题,无需额外判断 j != i 。
- 边界确认 :题目保证恰有一个答案,因此循环体内一定会在某次迭代返回;若允许无解,则循环结束后 return 空列表。
常见陷阱
- 先存后查导致自我匹配 :若写成先 seen[x] = i 再查 target - x ,当 target == 2 * x 时会用同一个元素两次,得到 [i, i] 的错误答案。
- 返回值的含义 :题目要求返回 下标 而非值。若面试官要求返回值本身(如返回两数),需改用双指针 + 排序,此时顺序信息会丢失。
- 数组已排序的追问 :若输入有序,最优解是双指针,O(n) 时间、 O(1) 额外空间 ,优于哈希表;面试中主动区分「是否有序」是关键得分点。
- 重复元素 :若 nums 含重复值,字典会被后出现的下标覆盖,但因题目保证唯一答案,不影响正确性;若改成「返回所有对」,则需用「值 → 下标列表」。
参考实现
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
seen = {} # 值 -> 下标
for i, x in enumerate(nums):
need = target - x
if need in seen: # 先查:保证不会重复使用同一元素
return [seen[need], i]
seen[x] = i # 后存
return [] # 题目保证有解,此处仅为完整性