您的位置:首页 > 其它

LeetCode 1:《Two Sum》

2015-01-06 21:57 351 查看
编程思路:尽量使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode