給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。
函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2。
說明:
返回的下標值(index1 和 index2)不是從零開始的。
你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素。
示例:
輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。
numbers = [1,2,7,8,11, 15]
target = 9
class Solution:
def twoSum(self, list,allNum):
for i in range(len(list)):
if list[i] < allNum:
for j in list:
aa= list[i] + j
if allNum == aa:
print("i==={0} j==={1}".format(i,list.index(j)))
break
num=Solution()
num.twoSum(numbers,target)
輸出結果:i===0 j===3