您的位置:首页 > 其它

LeetCode——Two Sum

2015-09-17 18:59 477 查看

题目

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

思路

看完题目,第一想到的是分别求出所有可能的组合,显示这种肯定不行

然后想去看看有什么其他规定,比如都是正数,或者是已排序数列,然而发现都没有。

那一对一对的算肯定不行,然后想其他办法,当然最好是遍历一遍就找出来,那么我们通过正向走,向后找是遍历List,那么肯定是n(O),那么我们用一个map把前面的存起来。正向遍历,然后再去map中找互补的数。就是O(n)了。

解法

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
maps = {}
result = []
for i in range(len(nums)):
if maps.has_key(str(nums[i])):
first = int(maps[str(nums[i])])
result.append(first)
result.append(i+1)
return result
else:
num = target-nums[i]
maps[str(num)] = str(i+1)
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: