2019-11-25-Leetcode 两数之和

所用语言:python

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

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

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/two-sum

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法1:使用两个循环嵌套,逐个遍历数组,将符合的条件记录下来

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        a=list()

        for i in range(len(nums)):

            for j in range(i+1,len(nums)):

                if nums[i]+nums[j]==target:

                    return i,j

解法二:使用python中的‘in’条件语句:

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        for i in range(len(nums)):

            a=target-nums[i]

            if a in nums and nums.index(a)!=i:

                return i,nums.index(a)


解法三,使用字典查找:

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        hashmap={}

        for i,num in enumerate(nums):

            #if hashmap.get(target - num) is not None:

            if target-num in hashmap:

                return i,hashmap[target-num]

               # return i,hashmap.get(target-num)

            hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况


                                    解法一                   解法二                   解法三

 执行用时|内存消耗    3852ms|12,5MB     976ms|12.4MB    28ms|13.1MB

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,725评论 0 3
  • 15.三数之和 给定一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c ,使得a + b +...
    不爱去冒险的少年y阅读 338评论 0 0
  • <center>#104 Maximum Depth of Binary Tree</center> link D...
    铛铛铛clark阅读 1,609评论 0 0
  • 今天去老姨和舅舅家上庙,请了两个小时的假,都是老亲戚了。 几个姨姐妹都是一年见一次面,由于是长时间不见面,见面相互...
    悦如晨阅读 166评论 0 4
  • 1 我和小影认识快二十年了,从上学到毕业再后来参加工作,一直到谈婚论嫁,我们俩都几乎形影不离,被窝一起钻过无...
    舞月璎阅读 294评论 0 1