美文网首页
2019-01-25--两数之和

2019-01-25--两数之和

作者: Ribosome_He | 来源:发表于2019-01-25 13:42 被阅读0次

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

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

示例:

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

python3解答:

class Solution:

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        """

        暴力遍历,耗时高

        if not len(nums):

            return None

        for x in range(0,len(nums)):

            for y in range(0,len(nums)):

                if x == y:

                    continue

                if nums[x] + nums[y] == target:

                    return [x,y]

            return None

        """

        #用哈希表查找

        if not len(nums):

            return None

        hashmap = {}

        for x in range(0,len(nums)):

            com = target - nums[x]

            if com in hashmap.values():

                #根据值找键

                return [list(hashmap.values()).index(com),x]  

#com在hashmap.values()中的索引就是对应字典里的key值,所以不用再查找hashmap.keys()

            hashmap[x] = nums[x]

        return None

最优解使用哈希表查询,将列表nums的元素跟索引插入字典作为键值对,在插入字典前先判断字典中是否存在等于target减去当前元素值(target - nums[x])的值,若存在直接返回当前元素的索引跟字典中符合条件的值的键。

通过值获取字典中的键:

list(mydict.keys())[list(mydict.values()).index(2)]

python3中mydict.values()和mydict.keys()返回一个<class 'dict_values'>,使用list()转换为列表,keys跟values的元素索引一一对应。list(mydict.values()).index(2)返回值为2的索引,利用该索引找到对应的key值:list(mydict.keys())[index]。

PS:python2中mydict.values()和mydict.keys()返回一个列表,无需强制转换。

相关文章

  • 2019-01-25--两数之和

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

  • 两数之和(golang)

    原题:两数之和 关联:两数之和 II - 输入有序数组(golang)两数之和 IV - 输入 BST(golang)

  • 两数之和 II - 输入有序数组(golang)

    原题:两数之和 II - 输入有序数组 关联:两数之和(golang)两数之和 IV - 输入 BST(golan...

  • 浅入浅出实现一个异步求和函数

    简化:两数之和 我们先来简单的实现一个异步两数之和函数 加深:多数之和 上面我们实现了两数之和,然后扩展到多数之和...

  • 两数之和,三数之和

    转载:https://www.cnblogs.com/DarrenChan/p/8871495.html 1. 两...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • 「算法」两数之和 & 两数之和 II

    00001 两数之和 题目描述 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只...

  • 两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...

  • 两数之和

    两数之和 题目描述 Given an array of integers, return indices of t...

网友评论

      本文标题:2019-01-25--两数之和

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