LeetCode Python 001 TwoSum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
  • 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,并返回他们的下标。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = dict()
        for index,value in enumerate(nums):
            sub = target - value
            if sub in dic:
                return [dic[sub],index]
            else:
                dic[value] = index
  • enumerate() 的作用在于返回一个可遍历对象中的所用下标和数据:
    • enumerate(sequence, [start=0])
    • sequence – 一个序列、迭代器或其他支持迭代对象。
    • start – 下标起始位置。
>>>bark = ['汪', '汪汪', '汪汪汪', '汪汪汪汪']
>>>list(enumerate(bark))
[(0, '汪'), (1, '汪汪'), (2, '汪汪汪'), (3, '汪汪汪汪')]
>>>list(enumerate(bark, start=1))       # 下标从 1 开始
[(1, '汪'), (2, '汪汪'), (3, '汪汪汪'), (4, '汪汪汪汪')]
  • 使用朴素的遍历方法在数组非常大的情况下速度很不理想,所以需要用python的字典来加快速度。
  • 构建思路是:
    • 目标:A+B==target
    • 换一下位置:B==target-A
    • 翻译一下就是: A所期望的对象==target-A
    • 假设我们有一个字典,里面的对照关系不再是下标:数据,而是数据:下标,就能够一步获得下标。
    • 此时字典的结构是:{A1的数据(键):A1的下标(值),A2的数据:A2的下标……}
    • 之后,如果有任意存在于字典中的键出现,就代表着配对成功。
    • 整合到一次遍历数组nums之后,既是:
      • 如果target-i在字典里:配对成功,返回i的下标以及字典里target-i的值
      • 如果target-i不在字典里边:配对失败,字典里加入i的数据:i的下标
  • 整个过程可以想象成一个婚姻介绍所:
    • 如果客户A通过他的择偶条件(B==target-A)在我们的花名册上找不到心仪的对象,则客户在花名册上留下他的信息(A的数据)和手机号码(A的下标)。
    • 如果客户找到了心仪的对象,则直接拿走心仪对象的手机号码。
    • 此时,我们的感情顾问就可以记录他们两个的手机号码(下标),并向他们收取中介费。(return)

猜你喜欢

转载自blog.csdn.net/weixin_41084236/article/details/81135419