美文网首页
LeetCode-1 两数之和

LeetCode-1 两数之和

作者: FlyCharles | 来源:发表于2019-02-24 00:11 被阅读0次

1. 题目

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

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

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

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

2. 我的AC

推算一遍

i = 0, num = 2
dic[9-2] = 0, {7:0} # 7的match位在0处

i = 1, num = 7
return [0, 1]

----
i = 2, num = 11
dic[9-11] = 0, {-2:2}

i = 3, num = 15
dic[9-15] = 0, {-6:3}
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for i, num in enumerate(nums):
            if num in dic:
                return [dic[num], i]
            else:
                dic[target - num] = i

3. 小结

  1. 看到精练的代码不理解,可以按照程序一步步推演一遍,推完就懂了

相关文章

  • Leetcode-1:两数之和

    题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,...

  • LeetCode-1 两数之和

    题目:1. 两数之和 难度:简单 分类:数组,哈希表 解决方案:暴力求解、HashMap 从今天开始开启《Leet...

  • LeetCode-1 两数之和

    1. 题目 https://leetcode-cn.com/problems/two-sum/ 给定一个整数数组 ...

  • 【简单】Leetcode-1 两数之和

    题目描述 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 ...

  • 1、两数之和(leetCode-1)

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 ...

  • LeetCode-1 两数之和(python3)

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

  • 两数之和(golang)

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

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

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

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

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

  • 两数之和,三数之和

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

网友评论

      本文标题:LeetCode-1 两数之和

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