本文共 1001 字,大约阅读时间需要 3 分钟。
为了解决这个问题,我们需要在给定的整数数组中找到两个数,使得它们的和等于目标值,并返回这两个数的下标。我们可以通过优化的方法来解决这个问题,避免使用暴力枚举,从而提高效率。
我们可以使用哈希表(字典)来优化查找过程。具体步骤如下:
这种方法的时间复杂度为 O(n),空间复杂度为 O(n),其中 n 是数组的长度。这种方法在处理大数组时效率很高。
def twoSum(nums, target): num_to_indices = {} for index, num in enumerate(nums): if num in num_to_indices: num_to_indices[num].append(index) else: num_to_indices[num] = [index] for i in range(len(nums)): current = nums[i] complement = target - current if complement in num_to_indices: for j in num_to_indices[complement]: if j > i: return [i, j] return None
num_to_indices
字典用于存储每个数值对应的所有下标。通过遍历数组,我们将每个数及其下标添加到字典中。这种方法确保了在找到满足条件的两个数时,能够高效且准确地返回它们的下标。
转载地址:http://ylio.baihongyu.com/