您的位置:首页 > 编程语言 > Python开发

LeetCode Two Sum

2015-12-11 21:42 453 查看

LeetCode解题之Two Sum

原题

给一个int型数组,要求找出其中两个和为特定值的数的坐标。

注意点:

返回的坐标一要比坐标二小

最小的坐标是1,不是0

例子:

输入: numbers={2, 7, 11, 15}, target=9

输出: index1=1, index2=2

解题思路

第一遍遍历整个数组,用map记录数值和它的坐标,第二遍遍历数组,判断(目标数字-当前数字)是否在map中,如果在,且它的下标与当前数字的下标不相同,则说明存在这两个数,返回坐标。

AC源码

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_map = {}
for index, value in enumerate(nums):
hash_map[value] = index
for index1, value in enumerate(nums):
if target - value in hash_map:
index2 = hash_map[target - value]
if index1 != index2:
return [index1 + 1, index2 + 1]


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息