You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求三数之和的threeSum函数总是返回空列表问题求解

问题定位
  • 核心bug出现在循环的提前终止分支:if idx > len(nums) - 3:后直接执行无返回值的return,直接中断函数执行,不会走到最后return list(res)的逻辑,所以哪怕res中已经存入了符合条件的三元组,最终也只会返回空值,这就是你看到调试时res有值但输出为空的根本原因。
  • 次要问题:函数要求返回List[List[int]]类型,原代码直接把存元组的set转列表,返回的元素是元组而非列表,部分严格的判题程序会判定格式错误。
修复方案

把循环中的空return替换为break(或直接删除该判断,后续while循环的i<j条件会自动处理边界情况),最终返回时把元组转为列表即可。

修复后代码
from typing import List

def threeSum(self, nums: List[int]) -> List[List[int]]:
    nums.sort(reverse=True)
    res = set()
    for idx, num in enumerate(nums):
        if idx > len(nums) - 3:
            break
        i = idx + 1
        j = len(nums) - 1
        while i < j:
            s = nums[i] + nums[j] + nums[idx]
            if s == 0:
                res.add((nums[i], nums[j], nums[idx]))
                i += 1
                j -= 1
            elif s < 0:
                j -= 1
            else:
                i += 1
    return [list(item) for item in res]

内容的提问来源于stack exchange,提问作者PiyushK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:09:03