題目
給定一個列表和一個目標值N住闯,列表中元素均為不重復的整數(shù)铺敌。請從該列表中找出和為目標值N的兩個整數(shù),然后只返回其對應的下標組合椅棺。
注意:列表中同一個元素不能使用兩遍抡诞。
例如:
給定列表 [2, 7, 11, 15],目標值N為 18土陪,因為 7 + 11 = 18昼汗,那么返回的結果為 (1, 2)
給定列表 [2, 7, 11, 6, 13],目標值N為 13鬼雀,因為 2 + 11 = 13顷窒,7 + 6 = 13,那么符合條件的結果為 (0, 2)源哩、(1, 3)
實現(xiàn)思路1
- 利用
多層循環(huán)
來實現(xiàn) - 通過兩層遍歷鞋吉,第一層遍歷的元素下標為 i ,第二層遍歷的元素下標為 j
- i與j 不能為下標相同的同一元素励烦,再比較 i與j 的和是否等于目標值target
- 判斷下標組合是否在結果列表中谓着,如果不在則添加到結果列表中
代碼實現(xiàn)
def find_two_number(nums, target):
res = []
for i in range(len(nums)):
for j in range(len(nums)):
if i != j and nums[i] + nums[j] == target and (i, j) not in res and (j, i) not in res:
res.append((i, j))
return res
nums = [1, 2, 4, 3, 6, 5]
target = 7
res = find_two_number(nums, target)
print("列表中兩數(shù)之和為 {} 的下標組合為:{}".format(target, res))
實現(xiàn)思路2
- 利用
列表
來實現(xiàn),列表的 index() 方法僅返回指定值首次出現(xiàn)的位置 - 通過遍歷坛掠,得到每次遍歷時的元素下標 i 赊锚,對應的元素為 cur_num
- 利用目標值 target 減去 cur_num 治筒,得到另一個數(shù) other_num
- 判斷另一個數(shù) other_num 是否存在于當前列表中,如果存在則表示列表中有符合條件的兩個數(shù)舷蒲,即可把對應的下標組合添加到結果列表中
代碼實現(xiàn)
def find_two_number(nums, target):
res = []
for i in range(len(nums)):
cur_num, other_num = nums[i], target - nums[i]
if other_num in nums[i+1:]:
res.append((i, nums.index(other_num)))
return res
nums = [1, 2, 4, 3, 6, 5]
target = 7
res = find_two_number(nums, target)
print("列表中兩數(shù)之和為 {} 的下標組合為:{}".format(target, res))
實現(xiàn)思路3
- 利用
字典
來實現(xiàn) - 通過遍歷耸袜,得到每次遍歷時的元素下標 i ,對應的元素為 cur_num
- 利用目標值 target 減去 cur_num 牲平,得到另一個數(shù) other_num
- 判斷另一個數(shù) other_num 是否存在于當前字典 temp_dict 的鍵中堤框,如果不存在就把當前數(shù) cur_num 及其對應列表中的下標 i 作為鍵值對,存儲到字典中
- 如果字典 temp_dict 的鍵中存在另一個數(shù) other_num纵柿,則表示列表中有符合條件的兩個數(shù)蜈抓,即可把對應的下標組合添加到結果列表中
代碼實現(xiàn)
def find_two_number(nums, target):
res = []
temp_dict = {}
for i in range(len(nums)):
cur_num, other_num = nums[i], target - nums[i]
if other_num not in temp_dict:
temp_dict[cur_num] = i
else:
res.append((temp_dict[other_num], i))
return res
nums = [1, 2, 4, 3, 6, 5]
target = 7
res = find_two_number(nums, target)
print("列表中兩數(shù)之和為 {} 的下標組合為:{}".format(target, res))
更多Python編程題,等你來挑戰(zhàn):Python編程題匯總(持續(xù)更新中……)