您的位置:首页 > 其它

leetcode_Two sum

2017-05-16 12:32 381 查看
Problem:

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].

My solution:

lennum = int(input("the length of num:"))
target = int(input("目标为:"))
i = 0
num = []
while i<lennum:
print("第 ", i, "个数为:")
n = int(input())
num.append(n)
i=i+1
print(num)
for j in range(len(num)):
for k in range(j+1,len(num)):
if(num[j]+num[k]==target):
print("j:", j, "k:", k)
break
My solution could run but the time was exceeded. I found a proper solution and its time was accepted.The code was :

class Solution:
def twoSum(self, nums, target):
map = {}
for index,num in enumerate(nums):
if target - num in map:
return [map[target - num], index]
map[num] = index

"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: