需求
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [4, 11, 4, 15, 4],target = 8
因?yàn)?nums[0] + nums[2] = 4 + 4 = 8 ,所以返回 [0, 2]
解決方案
方法一
- 不重復(fù)利用同樣的元素,即不能自己加自己,同一個(gè)元素也不能使用超過1次;
- 每次輸出只對應(yīng)一個(gè)答案,即只有一對數(shù)據(jù)符合要求。
- 使用Python內(nèi)置函數(shù)
enumerate()
獲取數(shù)組元素(value)及對應(yīng)的索引(key); - 如果
target - value
在列表中,且其索引必須大于key
,同時(shí)key
不在target_list
中,則將key
和值target - value
在列表nums
中的索引位置,添加到target_list
中即可。 - 參考代碼
def two_sum(nums, target):
target_list = []
for key, value in enumerate(nums):
if (target - value) in nums[key+1:] and key not in target_list:
target_list.extend([key, key + 1 + nums[key+1:].index(target - value)])
return target_list
nums = [4, 11, 4, 15, 4]
target = 8
result = two_sum(nums, target)
print(result)
[0, 2]
方法二
- 方法二僅對數(shù)列遍歷一次,通過索引位數(shù)加一排除使用重復(fù)元素;
- 對數(shù)列遍歷后,將索引和值添加到字典中,同時(shí)對字典進(jìn)行遍歷,判斷target-num是否在字典中,如果在則可以同時(shí)2個(gè)元素的索引位置。
- 參考代碼
def two_sum(num, target):
d = {}
for index, dig in enumerate(nums):
item = target - dig
for key, value in d.items():
if value == item:
return (key, index)
d[index] = dig
nums = [4, 11, 4, 15, 4]
target = 8
result = two_sum(nums, target)
print(result)
(0, 2)
需求延伸
如果不要求每種輸入只會(huì)對應(yīng)一個(gè)答案,則結(jié)果可能有多對數(shù)據(jù),對方法(一)中的target_list
,通過列表推導(dǎo)式的方法,成對地輸出,參考代碼:
def get_target_index(nums, target):
target_list = []
for key, value in enumerate(nums):
if (target - value) in nums[key+1:] and key not in target_list:
target_list.extend([key, key + 1 + nums[key+1:].index(target - value)])
result = [target_list[x:x+2] for x in range(0, len(target_list), 2)]
return result
nums = [2, 6, 4, 11, 4, 15, 4]
target = 8
result = get_target_index(nums, target)
print(result)
[[0, 1], [2, 4]]