python - 为什么大小为 2 的列表不适用于此嵌套 for 循环

标签 python python-3.x

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

给定一个整数数组 nums 和一个整数目标,返回两个数字的索引,使它们相加等于目标。 您可以假设每个输入都有一个解决方案,并且您不能两次使用相同的元素。 您可以按任意顺序返回答案。

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)]
            

最佳答案

您的代码行为不符合预期的原因是 num.index(x) 返回列表中匹配元素的 first 索引。因此,如果列表中有重复的元素(如第三种情况),语句 if nums.index(x) != nums.index(y): 将永远不会返回 True.

关于python - 为什么大小为 2 的列表不适用于此嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72573490/

相关文章:

python - 如何在字典中存储 tkinter 按钮小部件?

python - 内置对象的属性赋值

python - 如何简化networkx图?

python - 将百分位值分配给python中的一长串股票

c - Linux Ubuntu 如何获取远程主机名

Python内部类自身

python - 在循环中使用 SQLAlchemy Session 对象提交数据时出现问题

python - 扭曲的网络代理

python - 迭代巨大的 XML 文件并获取值?

python - 如何使用时间而不使用按钮命令更改 tkinter 中的帧