题目链接: 1. 两数之和 - 力扣(LeetCode)
首先需要了解: HashMap的containsKey(Key)方法会判断哈希表中是否存在这个Key,返回类型为布尔型。 containsKey方法的时间复杂度是O(1)。
官方给出的方法二是采用哈希表,时间复杂度为O(n)
依然是通过for循环遍历数组,在开始遍历前先创建一个空的HashMap,
Map<Integer,Integer> table = new HashMap<Integer,Integer>();
在遍历每个元素时都要判断此HashMap中是否存在一个key(注意是key,不是value),使得key=target-nums[i],
if (table.containsKey(target-nums[i]))
如果不存在这样的一个key,则将(key: nums[i], value: i)放入HashMap中,
table.put(nums[i],i);
如果存在这样的一个key,则成功找到结果,返回 key对应的value(因为value中放的是下表) 和 i。
return new int[]{table.get(target-nums[i]),i};
完整代码如下
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> table = new HashMap<Integer,Integer>();
for (int i=0;i<nums.length;i++){
/* 注意:在第一次进入循环时,table中是空的。 */
if (table.containsKey(target-nums[i])){
return new int[]{table.get(target-nums[i]),i};
}else{
table.put(nums[i],i);
}
}
return new int[0];
}
}