题干
链接:https://leetcode-cn.com/problems/two-sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
代码
class Solution {
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);
}
throw new IllegalArgumentException("No two sum solution");
}
}
总结
- 利用哈希表直接寻址表的特性,把值当做关键字进行储存和搜索,以空间换时间,大大加快了运算速度。
- 把哈希表的初始化和检索(寻址)放在一个循环里做,先判断所需要的关键字是否存在,若存在,则直接结束循环,否则将元素的值和下标存入哈希表中。