classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) indices = list(range(n)) indices.sort(key=lambda i: nums[i])
for i, p1 inenumerate(indices): v2 = target - nums[p1] p2 = self._bin_find(nums, indices, v2, i + 1) if p2 isnotNone: return [p1, p2]
return []
def_bin_find(self, nums: List[int], indices: List[int], value: int, left: int) -> int | None: l = left if l >= len(indices) or (t := nums[indices[l]]) > value: returnNone elif t == value: return indices[l]
r = len(indices) - 1 if (t := nums[indices[r]]) < value: returnNone elif t == value: return indices[r]
while l <= r: m = (l + r) >> 1 if (t := nums[indices[m]]) == value: return indices[m] elif t < value: l = m + 1 else: r = m - 1
returnNone
快一些
可以利用哈希表 O(1) 查询时间的特点,把所有数字放进哈希表,然后直接利用哈希表查找 target - v 是否存在。
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: indices = {} half = target >> 1if target & 1 == 0elseNone for i, v inenumerate(nums): # Special treatment of `target / 2` when target is even. if half isnotNoneand v == half and v in indices: return [indices[v], i]
indices[v] = i
for i, v1 inenumerate(nums): if half isnotNoneand v1 == half: continue
v2 = target - v1 if v2 in indices: return i, indices[v2]