Two Sum 问题
Source: Dev.to

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