给定一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标

时间:2019-07-16 03:44:11

标签: python

我刚刚开始在一些leetcode项目上工作,并且遇到以下问题。

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

我使用了以下代码:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in nums:
            for x in nums:
                if i + x == target:
                    index1 = nums.index(x)
                    index2 = nums.index(i)
                    break
        answer = []
        answer.append(index1)
        answer.append(index2)
        return answer

,当我在浏览器中运行它时,每次得到的结果都与预期相同。 enter image description here

但是,当我提交我的解决方案时,它又出错了。 enter image description here

为什么我的解决方案失败了?

0 个答案:

没有答案