1. 程式人生 > >第一題:找出列表中兩元素的和為一定值的元素下標

第一題:找出列表中兩元素的和為一定值的元素下標

題目:
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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

# coding:gbk
L = [2, 7, 11, 15]
target = 9


for i_1 in range(len(L)):
    for i_2 in range(len(L)):
        M = L[i_1] + L[i_2]
        if M == target:
            if i_1 < i_2:     #假設不考慮同一元素的情況(target為偶數,無=),
                print([i_1, i_2])