leetcode python数组: 两数之和

v1.0

def twoSum(nums,target):

    lens = len(nums)

    for i in range(lens):

        for j in range(i+1,lens):

            if nums[i]+nums[j]==target:

                return i,j

遍历可通过时间过长

v2.0

def twoSum(nums,target):

    lens = len(nums)

    for i in range(lens):

        one = nums[i]

        two = target - nums[i]

        if two in nums:

            j = nums.index(two)

            if i!=j:

                return i,j

一次循环寻找确认是否存在另一个值

v3.0

def twoSum(nums,target):

    lens = len(nums)

    dic = {}

    for i in range(lens):

        two  = target - nums[i]

        if nums[i] in dic:

            return dic[nums[i]],i

        else :

            dic[two]=i

将可能需要求得的值存到字典里,如果出现目标结果,输出返回值

猜你喜欢

转载自blog.csdn.net/weixin_42454757/article/details/81556790