Codewars Python两个求和对某些测试用例不起作用

t8e9dugd  于 2023-01-29  发布在  Python
关注(0)|答案(2)|浏览(103)

这段Python代码在一些测试用例中无法运行,下面是问题的链接:https://www.codewars.com/kata/52c31f8e6605bcc646000082/train/python

def two_sum(nums, target):
    nums.sort()
    l = 0
    r = len(nums)-1
    while l < r:
        sum = nums[l] + nums[r]
        if sum == target:
            return [l, r]
        if sum > target:
            r -= 1
        if sum < target:
            l += 1
    return []

任何帮助都非常感谢!:)

sg24os4d

sg24os4d1#

您正在寻找的解决方案是:

def two_sum(nums, target):
    indices = {}
    for index, num in enumerate(nums):
        remainder = target - num
        if remainder in indices:
           return indices[remainder], index
        indices[num] = index
    return 0, 0

我还可以马上告诉您,在做任何其他事情之前对nums进行排序是不好的,因为原始索引可能会混淆。

dced5bon

dced5bon2#

def two_sum(numbers, target):
    for n1 in enumerate(numbers):
        for n2 in enumerate(numbers):
            if n1[0] != n2[0]:
                if (n1[1] + n2[1]) == target:
                    return [n1[0], n2[0]]

相关问题