Leetcode 001-twosum
Posted 依然冷月
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 001-twosum相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables
leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段