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'

    小结:

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

  • 相关阅读:
    消除左递归
    DFA最小化
    非确定的自动机NFA确定化为DFA
    正规式到正规文法与自动机
    正规文法与正规式
    词法分析程序的设计与实现
    4.文法和语言总结与梳理
    语法树,短语,直接短语,句柄
    语法
    第一次作业 编译原理概述
  • 原文地址:https://www.cnblogs.com/openqt/p/4034044.html
Copyright © 2011-2022 走看看