标签:style blog color io os ar for strong sp
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‘
小结:
这个问题不需要什么复杂算法,只要对数据结构熟悉并能灵活运用就可以解决。如果对编程语言也很熟稔,代码会非常简洁明了。
标签:style blog color io os ar for strong sp
原文地址:http://www.cnblogs.com/openqt/p/4034044.html