LeetCode 1. 两数之和

1. 两数之和

解题思路

利用哈希表,一次遍历即可完成。遍历时将 target - nums[i] 作为 key 存入哈希表,若当前元素已在表中则直接返回。

参考代码

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 secondValue = target - nums[i];
if(map.containsKey(secondValue)) {
return new int[] {i, map.get(secondValue)};
}
map.put(nums[i], i);
}
return new int[] {};
}
}

LeetCode 1. 两数之和
https://sowink.cn/2026/02/06/LeetCode-1-两数之和/
作者
Xurx
发布于
2026年2月6日
许可协议