解题思路
用map的key存储数组的值,value存储索引,把数组存储在哈希表中,那么只需找到你要找的目标数组所对应的数值,即可用哈希表找出对应的索引,易知哈希表的containsKey和get都为O(1),则只需遍历一次数组即可获得答案,时间复杂度为O(n)。
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < n; i++) {
int target_f =target - nums[i];//根据map的value获取key,可以用数组实现
if (hashMap.containsKey(target_f)&&hashMap.get(target_f)!=i)//以防【3,3】为00,本身
return new int[] {i,hashMap.get(target_f)};
hashMap.put(nums[i],i);
}
throw new IllegalArgumentException("no such num");
}
}
public static void main(String[] args) {
int [] nums = {2,7,11,15};
int target= 9;
TowNum towSum2 = new TowNum();
int[] ints = towSum2.twoSum(nums,target);
for (int anInt : ints) {//anInt 为数组中的每一个元素。
System.out.printf(anInt+"\t");
}
}
涉及知识点:
1.foreach()
for(类型 变量名:集合) { 语句块; }
只是用于遍历比较方便,但是没有索引下标,所以并不常用。
其中,“类型”为集合元素的类型,“变量名”表示集合中的每一个元素,“集合”是被遍历的集合对象或数组。每执行一次循环语句,循环变量就读取集合中的一个元素,其执行流程如图 1 所示。
2.IllegalArgumentException()传入一个字符串做所抛出的异常提醒:
3.HashMap的key和value都可为null,key不可重复,若重复,则相同的key值会被之后的value覆盖。