1. 程式人生 > 實用技巧 >Python程式設計題10--找出和為N的兩個數

Python程式設計題10--找出和為N的兩個數

題目

給定一個列表和一個目標值N,列表中元素均為不重複的整數。請從該列表中找出和為目標值N的兩個整數,然後只返回其對應的下標組合。

注意:列表中同一個元素不能使用兩遍。

例如:

給定列表 [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)

實現思路1

  • 利用 多層迴圈 來實現
  • 通過兩層遍歷,第一層遍歷的元素下標為 i ,第二層遍歷的元素下標為 j
  • i與j 不能為下標相同的同一元素,再比較 i與j 的和是否等於目標值target
  • 判斷下標組合是否在結果列表中,如果不在則新增到結果列表中

程式碼實現

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("列表中兩數之和為 {} 的下標組合為:{}".format(target, res))

實現思路2

  • 利用 列表 來實現,列表的 index() 方法僅返回指定值首次出現的位置
  • 通過遍歷,得到每次遍歷時的元素下標 i ,對應的元素為 cur_num
  • 利用目標值 target 減去 cur_num ,得到另一個數 other_num
  • 判斷另一個數 other_num 是否存在於當前列表中,如果存在則表示列表中有符合條件的兩個數,即可把對應的下標組合新增到結果列表中

程式碼實現

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("列表中兩數之和為 {} 的下標組合為:{}".format(target, res))

實現思路3

  • 利用 字典 來實現
  • 通過遍歷,得到每次遍歷時的元素下標 i ,對應的元素為 cur_num
  • 利用目標值 target 減去 cur_num ,得到另一個數 other_num
  • 判斷另一個數 other_num 是否存在於當前字典 temp_dict 的鍵中,如果不存在就把當前數 cur_num 及其對應列表中的下標 i 作為鍵值對,儲存到字典中
  • 如果字典 temp_dict 的鍵中存在另一個數 other_num,則表示列表中有符合條件的兩個數,即可把對應的下標組合新增到結果列表中

程式碼實現

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("列表中兩數之和為 {} 的下標組合為:{}".format(target, res))