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

2019-11-25-Leetcode 两数之和

作者: 猎人1987 | 来源:发表于2019-11-25 09:30 被阅读0次

所用语言: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

相关文章

  • 2019-11-25-Leetcode 两数之和

    所用语言:python 题目:给定一个整数数组 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-11-25-Leetcode 两数之和

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