zoukankan      html  css  js  c++  java
  • Two Sum [easy] (Python)

    由于题目说了有且只有唯一解,可以考虑两遍扫描求解:第一遍扫描原数组,将所有的数重新存放到一个dict中,该dict以原数组中的值为键,原数组中的下标为值;第二遍扫描原数组,对于每个数nums[i]查看target-nums[i]是否在dict中,若在则可得到结果。 
    当然,上面两遍扫描是不必要的,一遍即可,详见代码。

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            keys = {}
            for i in xrange(len(nums)):
                if target - nums[i] in keys:
                    return [keys[target - nums[i]], i]
                if nums[i] not in keys:
                    keys[nums[i]] = i
  • 相关阅读:
    for else
    改变注释字体颜色
    多继承
    模块的查找顺序
    如何跳出多层嵌套
    验证码书写
    正则表达式(一)
    四、列表与超链接
    三、表格与表单
    二、HTML入门
  • 原文地址:https://www.cnblogs.com/boluo007/p/9121324.html
Copyright © 2011-2022 走看看