leetcode中的sumtwo问题:嗨,我是Leetcode的新手,我正在尝试解决第一个问题

时间:2020-07-19 21:10:11

标签: python list

问题:给定一个整数数组,返回两个数字的索引,这样它们加起来便成为一个特定的目标。给定nums = [2,7,11,15],target = 9,因为nums [0] + nums [1] = 2 + 7 = 9 返回[0,1]。我收到“ IndexError:列表索引超出范围”的错误消息,我的代码有什么问题?

以下是我的代码:

def sumtwo():
    arr = [1,2,5,3,4]
    l = []
    target = 6
    
    for i in arr[0:-1]:
        for k in arr[i+1:]:
            if arr[i] + arr[k] == target:
                l.append([i,k])
            else:
                continue
                
    return l

sumtwo()
   

1 个答案:

答案 0 :(得分:0)

您的初审并不差。但是,这里我们要解决O(N)时间复杂度的问题。这会通过:

class Solution:
    def twoSum(self, nums, target):
        indices = {}
        for index, num in enumerate(nums):
            if target - num in indices:
                return indices[target - num], index
            indices[num] = index

我的猜测是,您当前计划实现的类似于:

def sumtwo():
    arr = [1, 2, 5, 3, 4]
    l = []
    target = 6

    for i in range(len(arr)):
        for k in range(i + 1, len(arr)):
            if arr[i] + arr[k] == target:
                l.append([i, k])
            else:
                continue

    return l


print(sumtwo())

但是,这不会返回所需的输出。


参考文献

  • 有关其他详细信息,请参见Discussion Board。有许多languages和说明,有效的算法以及渐近time / space复杂度分析 1,{{3 }}

  • 对于2,我们想根据标准和约定编写interviewsbug-free代码(例如clean {{3 }}, 1 2 1 2 1 2 1 2 1 1 {{3 }} )。

  • 蛮力算法通常会被1个问题接受。对于1问题,大约90%的时间里,蛮力算法失败的原因主要是easy(TLE),而失败的原因是内存超出限制(MLE)错误。对于访谈,通常需要最佳和高效的算法,尤其是如果问题是medium级别时。


快乐编码! ˆ_ˆ