您的位置:首页 > 编程语言 > Go语言

Leetcode-Algorithms Two Sum

2017-02-26 11:13 330 查看
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

给出一个integer数列和一个integer,return一个包含 在给出的数列中两个数之和是给出的integer的index的 数列。只有唯一解。

这是一个最简单的方法,但是runtime太高。

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for p1 in range(len(nums)):
for p2 in range(p1+1,len(nums)):
if((nums[p1]+nums[p2]) == target):
return [p1,p2]


用哈希runtime会快很多因为只有一个loop。

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i


当list的数不在dict的时候,target减这个数的值为key,value为此数。当list的数为在dict为key的时候查找就完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: