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

LeetCode两数之和问题遇Time Limit Exceeded求助

Two Sum超时问题求助

我在做Two Sum题目时,小测试用例运行正常,但处理长度为19999的测试用例时,LeetCode返回Time Limit Exceeded。本地环境虽然能输出结果[9998, 9999],但耗时很长。以下是我写的三段代码,请求帮忙解决超时问题:

初始本地调试版

x = 0
y = 1
while x < len(nums):
    if x == y:
        y += 1
    if (nums[x] + nums[y]) == target:
        L = [x, y]
        print(L)
        break
    if y == len(nums) - 1:
        x += 1
        y = 0
    if (nums[x] + nums[y]) == target:
        L = [x, y]
        print(L)
        break
    #if x == len(nums) - 1:
    #    y += 1
    #    x = 0
    elif (nums[x] + nums[y]) == target:
        L = [x, y]
        print(L)
        break
    y += 1

LeetCode提交版

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        x = 0
        y = 1
        while x < len(nums):
            if x == y:
                y += 1
            if (nums[x] + nums[y]) == target:
                L = [x, y]
                return L
                break
            if y == len(nums) - 1:
                x += 1
                y = 0
            if (nums[x] + nums[y]) == target:
                L = [x, y]
                return L
                break    
            #if x == len(nums) - 1:
            #    y += 1
            #    x = 0
            if (nums[x] + nums[y]) == target:
                L = [x, y]
                return L
                break
            y += 1

更新版代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        x = 0
        y = 1
        while x < len(nums):
            if (nums[x] + nums[y]) == target:
                L = [x, y]
                return L
            if y == len(nums) - 1:
                x += 1
                y = x + 1
            if (nums[x] + nums[y]) == target:
                L = [x, y]
                return L
            y += 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:50:34