#coding: utf-8
"""
1. Two Sum
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].
"""
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
# 所需目標(biāo)數(shù)字典{所需目標(biāo)數(shù):位置,.....}
target_dict = {}
for i in range(len(nums)):
# 若第i個數(shù) == 某個位置的所需目標(biāo)數(shù),
# 則 target = 某個位置所需的目標(biāo)數(shù)(第i個數(shù))
# + nums[target_dict[nums[i]]]
# target_dict[nums[i]] = 某個位置
if nums[i] in target_dict:
return [target_dict[nums[i]], i]
else:
# 所需目標(biāo)數(shù) = target - 當(dāng)前位置數(shù)
target_dict[target - nums[i]] = i
1.Two Num
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門仰楚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事侨嘀。” “怎么了咬腕?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長涨共。 經(jīng)常有香客問我,道長举反,這世上最難降的妖魔是什么? 我笑而不...
- 正文 為了忘掉前任火鼻,我火速辦了婚禮雕崩,結(jié)果婚禮上魁索,老公的妹妹穿的比我還像新娘盼铁。我一直安慰自己粗蔚,他們只是感情好饶火,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著趁窃,像睡著了一般。 火紅的嫁衣襯著肌膚如雪醒陆。 梳的紋絲不亂的頭發(fā)上裆针,一...
- 文/蒼蘭香墨 我猛地睜開眼攒岛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了胞锰?” 一聲冷哼從身側(cè)響起灾锯,我...
- 正文 年R本政府宣布恕稠,位于F島的核電站,受9級特大地震影響扶欣,放射性物質(zhì)發(fā)生泄漏鹅巍。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一料祠、第九天 我趴在偏房一處隱蔽的房頂上張望骆捧。 院中可真熱鬧,春花似錦髓绽、人聲如沸敛苇。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽枫攀。三九已至,卻和暖如春株茶,著一層夾襖步出監(jiān)牢的瞬間来涨,已是汗流浹背。 一陣腳步聲響...