LeetCode 1 两数之和

作者: AiFany | 来源:发表于2019-04-28 16:40 被阅读3次
1556439482(1).png

1 两数之和

一、题目

给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

  • 示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

二、Python3程序

  • 知识点:数组,哈希表
# -*- coding:utf-8 -*-
# &Author  AnFany
# 1_Two_Sum 两数之和

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 创建nums中的值与索引的字典
        nums_dict = {}
        for i in range(len(nums)):
            number = nums[i]
            if target - number in nums_dict:
                return [nums_dict[target - number], i]
            else:
                nums_dict[number] = i

点击获得更多编程练习题。欢迎Follow,感谢Star!!! 扫描关注微信公众号pythonfan,获取更多。

image image

相关文章

网友评论

    本文标题:LeetCode 1 两数之和

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