LeetCode:1. Two Sum - Python

1. 两数之和

问题描述:

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

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

示例:

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

问题分析:

写论文闲来无趣,自嘲的笑一下,这个题目有点古老了,为了和上一篇文章对应,顺便总结了。

(1)借用字典(或者hash)的方法。

(2)扫描一边数组,用字典中,k存储target - nums[i],用v存储i,在遍历的过程中,很显然,要判断nums[i]是否已经存在字典里面了,如果存在说明答案已经出来了。

(3)如果,遍历完了,没有答案就直接返回[-1, -1]

Python3实现:

# @Time   :2018/06/17
# @Author :LiuYinxing
# hash法


class Solution:

    def twoSum(self, num, target):
        dicts = {}
        for i in range(len(num)):
            if num[i] not in dicts:
                dicts[target - num[i]] = i
            else:
                return [dicts[num[i]], i]
        return [-1, -1]


if __name__ == '__main__':

    solu = Solution()
    output = solu.twoSum([3, 2, 4], 6)
    print(output)

声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。

题目链接

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/86518711