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

为何我的3Sum问题代码无法处理[0,0,0]这类测试用例?

问题定位与修复方案

核心问题分析

当输入nums = [0,0,0]时,你的代码返回空列表的原因有两个关键逻辑错误:

  1. 提前跳过重复元素导致索引重合:在双指针移动前就执行跳过重复元素的操作,当low=1、high=2时,第一个while循环会因nums[1]==nums[2]把low直接加到2,此时low和high相等,触发low != high的判断条件不成立,无法将[0,0,0]加入结果。
  2. 冗余的索引判断:low != high的判断完全没必要,且提前跳重复的逻辑破坏了合法的多相同元素三元组的索引关系——原本i=0、low=1、high=2是三个合法不同索引,却被提前操作变成low=high,导致无法触发添加逻辑。

修复后的代码

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        nums.sort()
        result = []
        
        for i in range(n):
            # 跳过i的重复元素,避免重复计算
            if i > 0 and nums[i] == nums[i-1]:
                continue
            target = -nums[i]
            low, high = i + 1, n - 1
            
            while low < high:
                current_sum = nums[low] + nums[high]
                if current_sum < target:
                    low += 1
                elif current_sum > target:
                    high -= 1
                else:
                    # 先将有效三元组加入结果
                    result.append([nums[i], nums[low], nums[high]])
                    # 跳过low的重复元素
                    while low < high and nums[low] == nums[low+1]:
                        low += 1
                    # 跳过high的重复元素
                    while low < high and nums[high] == nums[high-1]:
                        high -= 1
                    # 移动指针寻找下一组可能
                    low += 1
                    high -= 1
        return result

关键修复点说明

  • 调整去重时机:先判断找到有效三元组后,再跳过重复的low和high元素,既避免重复结果,又不会破坏合法的多相同元素三元组(比如[0,0,0])。
  • 添加i的去重:在循环开头直接跳过与前一个元素相同的i,省去了最后额外的去重步骤,同时提升代码效率。
  • 移除冗余判断:去掉low != high、high != i、low != i的判断,因为low初始值是i+1,high始终大于low,三个索引天然不同,无需额外校验。

测试验证

输入nums = [0,0,0]时,执行流程:

  1. i=0,nums[i]=0,无重复跳过,target=0,low=1,high=2。
  2. current_sum=0+0=0等于target,将[0,0,0]加入结果。
  3. 跳过low的重复:low=1,nums[1]==nums[2],low变为2;跳过high的重复:low=2不小于high=2,循环不执行。
  4. low +=1变为3,high -=1变为1,循环结束。
  5. 最终返回[[0,0,0]],符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:25:59