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].
Related Topics: Hash Table
、Array
這一題算是 LeetCode 中的 Hello World 吧,網路上還流傳著平生不識 TwoSum,刷盡 LeetCode 也枉然這句話呢,可見這題是多麼的廣為人知(?)
簡單來說這題是要從給定陣列中找出兩個數字,其總和為給定的 target,最後返回這兩個數字的索引值。每題必定只有一個解,且每個數字並不會被重複使用。
最直覺想到的當然是暴力法,但果不其然 Time Limit Exceeded,畢竟用暴力法的時間複雜度是
class Solution:
def cal_sum(self, num_1 , num_2):
return num_1 + num_2
def twoSum(self, nums, target):
size = len(nums)
for idx1 in range (size) :
num_1 = nums[idx1]
for idx2 in range(idx1+1 ,size):
num_2 = nums[idx2]
s = self.cal_sum(num_1,num_2)
if s == target:
return [idx1,idx2]
raise RuntimeError("No two sum solution")
既然暴力法時間複雜度爆表,那就拿空間換取時間吧!另外設立一個 HashMap 儲存走訪過的結果,當一個數字進來後去檢查差值是否存在 HashMap 中,若存在則回傳結果,實做步驟如下:
class Solution:
def twoSum(self, nums, target):
keys = {}
for idx, value in enumerate(nums):
diff = target - value
if diff in keys:
return [keys[diff], idx]
keys[value] = idx
本文作者: 辛西亞.Cynthia
本文連結: 辛西亞的技能樹 / hackmd 版本
版權聲明: 部落格中所有文章,均採用 姓名標示-非商業性-相同方式分享 4.0 國際 (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!