1. 两数之和
- 题号:1
- 来源:LeetCode
- 难度:简单
- 标签:
哈希表数组双指针 - 语言:TypeScript · Python · Java
- 解法:4 个
- 作者:lmliheng
- 最近更新:2026-09-30
解法一
TypeScript · O(n) 时间 · O(1) 空间 · 更新于 2026-09-30
这里的数组是一个有序数组,先假定是非递减的
typescript
/**
* @difficulty easy
* @tags 双指针,数组
* @time O(n)
* @space O(1)
* @note 这里的数组是一个有序数组,先假定是非递减的
*
* @两数之和(改进1)
* 时间复杂度O(n),空间复杂度O(1)
*/
function twoSum(nums: number[], target: number) {
let n = nums.length
for (let i = 0; i < n; i++) {
for (let j = n - 1; j > i; j--) {
if (nums[i] + nums[j] < target) {
break
} else if (nums[i] + nums[j] > target) {
continue
} else {
return [i, j]
}
}
}
}解法一
TypeScript · O(n) 时间 · O(n) 空间 · 更新于 2026-09-30
遍历时用哈希表存补数,命中即返回
typescript
/**
* @difficulty easy
* @tags 哈希表,数组
* @time O(n)
* @space O(n)
* @note 遍历时用哈希表存补数,命中即返回
*
* @两数之和
* 时间复杂度O(n),空间复杂度(n)
*/
function twoSum(nums: number[], target: number) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
if (map.has(nums[i])) {
return [map.get(nums[i]), i];
}
map.set(target - nums[i], i);
}
return [];
}Python
Python · O(n) 时间 · O(n) 空间 · 更新于 2026-09-29
边遍历边在哈希表里查补数
python
"""
@difficulty easy
@tags 哈希表,数组
@time O(n)
@space O(n)
@note 边遍历边在哈希表里查补数
两数之和
lc 1
"""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_map={}
for index,num in enumerate(nums):
deleteNum=target-num
if deleteNum in nums_map:
return [index,nums.index(deleteNum)]
else:
nums_map[num]=index源码:python/leetcode/hot100/1.py
Java
Java · O(n) 时间 · O(n) 空间 · 更新于 2026-09-27
一次遍历,哈希表存「补数 → 下标」,命中即返回
java
/**
* @lc 1
* @title 两数之和
* @difficulty easy
* @tags 哈希表,数组
* @time O(n)
* @space O(n)
* @note 一次遍历,哈希表存「补数 → 下标」,命中即返回
*/
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[0];
}
}源码:Java/src/main/java/com/algorithm/leetcode/TwoSum.java
在 GitHub 上查看题目所在目录:lmliheng/algorithm