Python 中的两个和
pythonserver side programmingprogramming更新于 2025/10/26 14:04:17
假设我们有一个整数数组。我们必须返回两个整数的索引,这样如果我们将它们相加,我们就会达到给定的特定目标。这里我们将采取一个假设,即数组中始终会有一个唯一的解决方案,因此不会有两组针对同一目标的索引。
例如,假设数组为 A = [2, 8, 12, 15],目标和为 20。那么它将返回索引 1 和 2,即 A[1] + A[2] = 20。
为了解决这个问题,我们将循环遍历数组的每个元素。因此请按照以下步骤解决此问题。
- 定义一个名为 res 的映射来保存结果
- 对于范围为 0 到 n 的索引 i – 1(其中 n 是数组中元素的数量)
- 如果 target − A[i] 存在于 res 中
- 返回 res[target − A[i]] 和 i 作为索引
- 否则将 i 放入 res 中,作为 res[A[i]] − = i
- 如果 target − A[i] 存在于 res 中
让我们看一下实现过程以便更好地理解
示例
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
required = {}
for i in range(len(nums)):
if target - nums[i] in required:
return [required[target - nums[i]],i]
else:
required[nums[i]]=i
input_list = [2,8,12,15]
ob1 = Solution()
print(ob1.twoSum(input_list, 20))
输入
input_list = [2,8,12,15] target = 20
输出
[1, 2]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

