Two Sum 问题

发布: (2026年4月4日 GMT+8 10:53)
3 分钟阅读
原文: Dev.to

Source: Dev.to

Two sum 问题的封面图片

Hello! Today I will explain how to solve the Two Sum problem. I believe most developers have seen this problem before—either when they first started practicing coding or when preparing for job interviews.

For those in the software industry who haven’t solved this problem yet, I’ll show you how to approach it step by step.

Let’s get started.

Question

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example

Input: nums = [2,11,15,7], target = 9
Output: [0,3]
Explanation: Because nums[0] + nums[3] == 9, we return [0, 3].

Solution

function twoSum(nums, target) {
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] === target) {
                return [i, j];
            }
        }
    }
    return [];
}

const nums = [2, 11, 15, 7];
const target = 9;

console.log(twoSum(nums, target)); // Answer: [0, 3]

Explain the solution

  • 创建一个接受两个参数 numstarget 的函数。
  • 使用两层循环在数组中寻找两数之和等于目标值的数对:
    • 外层循环遍历数组的每个元素。
    • 内层循环检查当前外层索引之后的元素。
  • 例如,对于 [2, 11, 15, 7]
    • 当外层循环指向 2 时,内层循环会检查 11157
  • 在内层循环中,判断这两个数的和是否等于目标值。
  • 若相等,返回它们的索引。
  • 若遍历完所有可能仍未找到匹配对,返回空数组。
  • 就是这么简单!

Performance consideration

This solution is easy to understand and works correctly, but it is not efficient. It uses a time complexity of O(n²) because it checks every possible pair.

In the next article, I will show you a more efficient solution that reduces the time complexity—this will be useful for interviews and real‑world applications.

Thanks for reading, and keep learning!

Reference

https://leetcode.com/problems/two-sum/description/

0 浏览
Back to Blog

相关文章

阅读更多 »

PWC 367 重叠的奇异现象

任务 1 – Maximum Odd Binary 现在是 Artemis 2 任务登月的那一周,我们遇到了一个关于奇数的问题。我把它称为 Space Oddity。你是...

每周挑战:最大冲突

抱歉,我没有看到需要翻译的完整文本。请您提供完整的摘录或摘要内容,我才能为您进行翻译。

JavaScript 中的解构赋值

你有没有写过这样的代码?js // 重复提取 const numbers = 10, 20, 30; const first = numbers0; const second = numbers1; 它能工作——但它是……