码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 001-twosum

时间:2018-05-28 22:43:26      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:div   记录   turn   add   example   dex   input   print   bec   

 1 #Given an array of integers, return indices of the two numbers such that they add up to a specific target.
 2 #You may assume that each input would have exactly one solution, and you may not use the same element twice.
 3 #Example:
 4 #Given nums = [2, 7, 11, 15], target = 9,
 5 #Because nums[0] + nums[1] = 2 + 7 = 9,
 6 #return [0, 1].
 7 def twoSum(nums, target):
 8     dic = dict()
 9     for index,value in enumerate(nums):
10         sub = target - value
11         if sub in dic:
12             return [dic[sub],index]
13         else:
14             dic[value] = index
15 L=[1,2,3,5]
16 print(twoSum(L,7))

 这道题的解题思路很简单,利用python中的字典记录记录下每个元素出现的位置,也就是其他语言中的哈希表。

Leetcode 001-twosum

标签:div   记录   turn   add   example   dex   input   print   bec   

原文地址:https://www.cnblogs.com/hustcser/p/9102445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!