啦啦啦,歡迎開啟LeetCode刷題的旅程,這將是一段漫長而又艱辛的旅程。這道Two Sum的題目作為LeetCode的開篇之題,乃是經典中的經典,正所謂‘平生不識TwoSum,刷盡LeetCode也枉然’,就像英語單詞書的第一個單詞總是Abandon一樣,很多沒有毅力堅持的人就只能記住這一個單詞,所以通常情況下單詞書就前幾頁有翻動的痕跡,后面都是嶄新如初,道理不需多講,雞湯不必多灌,明白的人自然明白。
題目:
給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
參考代碼:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
如果還想獲得更多leetcode 的參考答案,請跟我聯系ai_hellohello