1.两数之和
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].
任务:给定一个数组,和一个目标的数值,给出相加可以得到目标数值的下标。
暴力搜索
复杂度\(O(n^2)\)
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target
return [i,j]
利用hash表
建立一个哈希表存储了数值和下标。复杂度可以为\(O(n)\)
def twosum_hashmap(nums, target):
'''
input:
nums - list of numbers to calc
target - target value
output:
[a,b] - index of required numbers
'''
dataset = {}
for index in range(len(nums)):
dataset[(nums[index])] = index
for value in nums:
if (target - value) in dataset and \
(value) in dataset \
and dataset[(value)] != dataset[(target-value)]:
return [dataset[(value)], dataset[(target-value)]]
return []
one-pass
def twosum_hashmap_onepass(nums,target):
dataset={}
for index in range(len(nums)):
if (target - nums[index]) in dataset:
return [index, dataset[(target-nums[index])]]
else:
dataset[(nums[index])] = index

浙公网安备 33010602011771号