LeetCode第334题代码本地正确但提交返回False求助
LeetCode 334题代码排查:本地与线上结果不一致
我运行以下increasingTriplet函数时,测试用例[14,22,21,11,90]本地返回True,但提交到LeetCode第334题时该用例返回False,请帮忙排查问题:
def increasingTriplet(nums): """ :type nums: List[int] :rtype: bool """ x = sorted(list(set(nums))) if len(x) < 3: return False map = {} for i in x: map[i] = sorted([j for j, num in enumerate(nums) if num == i]) while len(map.keys())+i>2: i = 0 least = map[min(map.keys())][0] for key2 in list(map.keys())[1:]: if least < map[key2][-1]: i += 1 least = [y for y in map[key2] if y > least][0] if i > 1: return True map.pop(min(map.keys())) return False
提交截图显示该测试用例在LeetCode上判定为False。
问题排查与修复
1. 字典遍历顺序依赖的逻辑错误
代码中for key2 in list(map.keys())[1:]依赖字典key的顺序为从小到大,但Python3.7之前的版本中字典是无序的,LeetCode环境可能使用该版本,导致遍历顺序并非按key递增,从而无法正确匹配递增三元组的索引顺序。
2. 循环条件逻辑混乱
while len(map.keys())+i>2的条件完全错误:i是循环内部变量,第一次进入循环时i的值来自之前的for循环(如测试用例中为90),后续循环依赖i被重置为0后的计算结果,逻辑完全不可靠,可能导致循环异常退出或错误执行。
3. 未处理索引列表为空的异常
当[y for y in map[key2] if y > least]为空时,取[0]会触发IndexError,虽然测试用例未触发,但属于潜在bug。
修复后的代码
def increasingTriplet(nums): """ :type nums: List[int] :rtype: bool """ unique_sorted = sorted(list(set(nums))) if len(unique_sorted) < 3: return False idx_map = {} for num in unique_sorted: idx_map[num] = sorted([j for j, n in enumerate(nums) if n == num]) # 只要不同元素数量大于2,就继续尝试匹配三元组 while len(idx_map) > 2: count = 0 min_key = min(idx_map.keys()) last_idx = idx_map[min_key][0] # 显式按key从小到大遍历,避免字典顺序依赖 for key in sorted(idx_map.keys())[1:]: if idx_map[key][-1] > last_idx: count += 1 # 安全获取第一个大于last_idx的索引,避免空列表报错 try: last_idx = next(y for y in idx_map[key] if y > last_idx) except StopIteration: continue if count > 1: return True idx_map.pop(min_key) return False
更高效的标准解法
原代码逻辑复杂且时间/空间效率较低,推荐使用O(n)时间、O(1)空间的标准解法,完全避免环境依赖问题:
def increasingTriplet(nums): first = second = float('inf') for num in nums: if num <= first: first = num elif num <= second: second = num else: return True return False
内容的提问来源于stack exchange,提问作者Purnajyoti Bhaumik
相关产品推荐
相关产品推荐

