https://leetcode.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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题目分析:从整型数组中返回和为给定值的两个数的下标,每个下标元素只能使用一次
暴力法:遍历每个元素 x,并查找是否存在一个值与 target - x 相等的目标元素,两层for循环时间复杂度 O(n^2)
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(target == nums[i] + nums[j]){
return new int[]{i,j};
}
}
}
引入Hash表:建立数组中的每个元素与其索引的映射,先循环将元素放入map,再循环检测是否已经存在当前元素所对应的目标元素;
保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表,通过以空间换取速度的方式,我们可以将查找时间从 O(n)降低到 O(1); 哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找;
("近似" 是因为一旦出现冲突,查找用时可能会退化到 O(n),但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1))
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
//每个元素只能用一次
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
在测试参数有多个答案时,因为map中后续索引被覆盖的缘故,重复元素取的是最后一个的索引,如 nums = [2,5,5,6], target = 11,返回[2,3]而不是[1,3];
优化:在进行迭代并将元素插入到表中的同时,检查表中是否已经存在当前元素所对应的目标元素
static 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");
}