编程思路:尽量使用Python内置的函数,不要自己写浪费时间的多重循环,容易Time Limit Exceed!由题意假设只有一个结果,所以找到后及时退出!
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
t = ()
for index_1, value_1 in enumerate(num):
value_2 = target - value_1
# 如果两个数相等
if value_1 == value_2:
# 出现多于一次
if num.count(value_1) > 1:
# 从第一个索引的下一个位置检索
index_2 = num.index(value_2, index_1+1)
t = (index_1+1, index_2+1)
break
else:
if value_2 in num:
index_2 = num.index(value_2, index_1+1)
t = (index_1+1, index_2+1)
break
return t