美文网首页
1. 两数之和

1. 两数之和

作者: 不湿的尿布湿 | 来源:发表于2020-02-29 11:36 被阅读0次

    一、题目

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

    难度:简单
    链接:两数字和#

    二、示例

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    三、解答

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            dict = {}
            for i, m in enumerate(nums):
                dict[m] = i
            for i, m in enumerate(nums):
                j = dict.get(target - m)
                if j is not None and i != j:
                    return [i, j]
    

    相关文章

      网友评论

          本文标题:1. 两数之和

          本文链接:https://www.haomeiwen.com/subject/spwuhhtx.html