zoukankan      html  css  js  c++  java
  • Two Sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    分析:

    要从一个列表中找到两个数之和等于给定的值,要求的输出是两个数在列表里的位置。

    我们需要一个数据结构,能够快速查找某个数是否存在,并且还可以记录这个数的索引位置,字典对象再合适不过了。

    基本的算法是,先对列表遍历一次,生成一个dict对象,key是数值,value是数值在列表中的位置,一行Python语句就可以解决,

    map = dict(zip(num, range(1, len(num) + 1)))

    然后再遍历列表,用给定的值减去当前列表元素,看结果是否在dict对象中,如果找到,就返回当前列表元素位置和dict对象的value所组成的二元组。

    class Solution:
    
        # @return a tuple, (index1, index2)
        def twoSum(self, num, target):
            map = dict(zip(num, range(1, len(num) + 1)))
    
            for i, a in enumerate(num, 1):
                b = target - a
                if b in map and map[b] != i:
                    return (i, map[b])
            return (0, 0)
    
    if __name__ == '__main__':
        s = Solution()
        assert s.twoSum([2, 7, 11, 15], 9) == (1, 2)
        assert s.twoSum([0, 1, 2, 0], 0) == (1, 4)
        print 'PASS'

    小结:

    这个问题不需要什么复杂算法,只要对数据结构熟悉并能灵活运用就可以解决。如果对编程语言也很熟稔,代码会非常简洁明了。

  • 相关阅读:
    linux查看内存占用情况
    tomcat JVM内存 配置
    Linux中iptables设置详细
    asmack xmpp 获取离线消息
    linux查看端口被哪个服务占用的命令
    Redis 3.0版本启动时出现警告的解决办法
    redis中密码设置
    linux安装(Ubuntu)——(二)
    Linux简介——(一)
    Android控件——ToggleButton多状态按钮(实现灯泡的开关)
  • 原文地址:https://www.cnblogs.com/openqt/p/4034044.html
Copyright © 2011-2022 走看看