topic
Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array indices.
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
brute force enumeration
Two layers of for loops are traversed one by one, O(n^2)
def twoSum(ary,target):
for i in range(len(ary)):
for j in range(i+1,len(ary)):
if ary[i]+ary[j]==target:
return [i,j]
return []
Dictionary simulation hash table
A layer of for loop traversal, the element value is the key and the table below is the value stored in the dictionary. O(n)
def twoSum(ary,target):
hashTable = {}
for i, num in enumerate(ary):
if target-num in hashTable:
return [hashTable[target-num],i]
hashTable[num]=i
return []
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。