LeetCode by Python3想法读书

LeetCode 1 两数之和

2019-04-28  本文已影响3人  AiFany
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
上一篇 下一篇

猜你喜欢

热点阅读