LeetCode 1:《Two Sum》

来源:互联网 发布:关于数据爆炸 编辑:程序博客网 时间:2024/04/24 23:20

编程思路:尽量使用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 


0 0
原创粉丝点击