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

如何通过微小改动降低Two Sum代码运行时间?求高效算法优化建议

两数之和(Two Sum)问题

问题描述

给定一个整数数组 nums 和一个整数 target,返回两个数的下标,使它们的和等于 target。

  • 每个输入恰好有一个有效解,且不能重复使用同一个元素
  • 返回的下标顺序不限

示例

  • 示例1:输入 nums = [2,7,11,15],target = 9,输出 [0,1]

    解释:nums[0] + nums[1] == 9,因此返回 [0,1]

  • 示例2:输入 nums = [3,2,4],target = 6,输出 [1,2]
  • 示例3:输入 nums = [3,3],target = 6,输出 [0,1]

约束条件

  • 2 ≤ nums.length ≤ 10⁴
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • 仅存在一个有效答案

我的解决方案

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i < nums.length; i++) {
            for(int j = i + 1; j < nums.length; j++) {
                if(nums[i] == target - nums[j]) {  // 此处修改了判断条件
                    return new int[] {i, j};
                }
            }
        }
        return null;
    }
}

我发现仅仅把判断条件从 nums[i] + nums[j] == target 改成 nums[i] == target - nums[j],代码的运行时间就减少了一半。这是我做的第一道LeetCode题目,希望能得到一些寻找时间高效解法的建议。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:25:42