目录
一、题目
二、解题思路
通过使用哈希表来存储数组的元素以及它的索引
1.循环遍历数组,拿到每个元素 x
2.以target - x作为key 到 hash 表查找
(1)若没找到,将x作为key,它的索引作为value放入hash表
(2)若找到了,返回x和它配对数的索引即可
三、代码
class Solution {
//思路
//1.遍历数组,拿到每一个元素x
//2.以target - x为key到hash表中查找
//2.1找到了返回x和target - x的索引
//2.2找不到,则将nums[i]作为key,x为value放入hash表
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();//使用HashMap来存储值以及其索引
for (int i = 0; i < nums.length; ++i) {
int y = target - nums[i];
if (hashtable.containsKey(y)) {
return new int[]{hashtable.get(y), i};
}
else{
hashtable.put(nums[i], i);
}
}
return null;
}
}
文章介绍了如何利用哈希表在给定数组中寻找两个数,使得它们的和等于目标值。通过遍历数组,将元素和其索引存入哈希表,然后查找目标值减去当前元素的数,如果找到则返回对应索引,否则将当前元素存入表中。

260

被折叠的 条评论
为什么被折叠?



