Tp3.2 多資料庫連結
阿新 • • 發佈:2021-07-12
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