两数之和

两数之和

1、题目描述

2、解法

1:暴力枚举

枚举数组中的每一个数 x,寻找数组中是否存在 target - x

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int[] twoSum(int[] nums, int target) {
int nums_length = nums.length;
for (int i = 0; i < nums_length; ++i) {
for (int j = i + 1; j < nums_length; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}

2:哈希表

创建一个哈希表,对于每一个 x,首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。

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> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}


两数之和
http://example.com/2023/10/07/two-nums-sums/
作者
Z Z
发布于
2023年10月7日
许可协议