对于LeetCode上的二和问题,它说:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Input: nums = [2,7,11,15], target = 9
Input: nums = [3,2,4], target = 6
Input: nums = [3,3], target = 6

这三个问题的结果都是:

[0,1]
[1,2]
[0,1]

但出于某种原因,我的代码未能通过最后一个测试用例并打印出来:

[0,1]
[1,2]
[]

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        temp = 0
        tempValue = 0
        for x in nums:  # x is 3
            temp = target - x  # temp is 3
            for y in nums:  # y is 3
                if nums.index(x) != nums.index(y):
                    tempValue = x + y  # 3+3 = 6
                    
                    if tempValue == target:
                        return [nums.index(x), nums.index(y)]
            

推荐答案

您的代码中有很多样板文件.您应该避免不必要的临时变量,并将enumerate与数组索引一起使用以获取索引.

代码上需要两个for循环.一个将迭代完整列表,第二个将迭代完整列表,但从第一个循环计算的值的下一个位置开始.

代码:

def two_sum(nums: list[int], target: int) -> list[int]:
    for i, x in enumerate(nums):
        for j, y in enumerate(nums[i+1:]):
            if x + y == target:
                return [i, j+i+1]

您的代码失败,因为:

if nums.index(x) != nums.index(y):

在 case 3中始终为false.x和y始终为3,索引始终为0.

Python相关问答推荐

寻找Regex模式返回与我当前函数类似的结果

Pandas:计算中间时间条目的总时间增量

交替字符串位置的正则表达式

语法错误:文档. evaluate:表达式不是合法表达式

如何将相同组的值添加到嵌套的Pandas Maprame的倒数第二个索引级别

每次查询的流通股数量

Scipy差分进化:如何传递矩阵作为参数进行优化?

我如何处理超类和子类的情况

极点用特定值替换前n行

如何在Polars中处理用户自定义函数的多行结果?

IpyWidget Select 框未打开

突出显示两幅图像之间的变化或差异区域

将.exe文件从.py转换后出现问题.";ModuleNotFoundError:没有名为';Selify;的模块

使用loc计算特定行的平均值,loc找不到行值

如果init被重载,如何输入提示一个基于init的函数的返回类型

Django LoginView中的一个大问题

绘制的烛台图在绘制其他数据后消失

NumPy使用其他2个3D数组和一个1D数组创建一个3D数组来区分

删除特定单词后面的单词

不理解它怎么会是索引错误:列出索引超出范围