LeetCode 1. Two Sum

🧠 思路总结

  • 用哈希表记录「值 -> 下标」
  • 遍历数组,每次看 target - nums[i] 在不在 map 里
  • 在的话直接返回两个下标;不在就把当前值加入 map
  • 模板题,很多 Two Sum 变种都能套这个写法

❗ 易错点 / 小坑

  • 题目保证只有一个答案,所以找到后可以直接 return
  • 不能先把所有数丢进 map 再找,否则会用到同一个元素两次
  • 注意:返回的是 下标,不是数值本身

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need)) {
return new int[]{map.get(need), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
}

LeetCode 1. Two Sum
https://powersixxx.github.io/leetcode-blog/2025/12/10/LeetCode-1-Two-Sum/
作者
Baowen Liu
发布于
2025年12月10日
许可协议