//import the HashMap,Map to avoid the compile error
//import java.util.Map;
//import java.util.HashMap;
public class Solution{
public int[] twoSum(int[]num, int target){ //twoSum方法
//用hashtable,建一个对象map
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<num.length; i++){
//因为是个动态查找,判断临时目标值存在不:临时目标值= target-num[i)
if(map.containsKey(target-num[i))//如果返回为真,存在这个差值
{
//返回这个目标值及其index i;
return new int[]{target-num[i],i};
}
//如果没有,返回为假,就压到map里面
map.put(num[i],i);
}
return null;
}
}
注释1:
HashMap与Map的理解:
HashMap 是 Map 接口的常用实现类(Map是一个接口),是一个键值对集合,
在数组中我们是通过数组下标来对其内容索引的,而在Map中我们通过对象来对 对象进行索引,用来索引的对象叫做key,其对应的对象叫做value。
eg: Map<String, Object> parameters = new HashMap<>();
parameters.put(“能力ID”, abilityId);
能力ID就是key,abilityId就是value,
HashMap中元素的排列顺序是不固定的.HashMap通过hashcode对其内容进行快速查找。
建议使用实现接口的方式使用Map,
如:Map<String, Object> element = new HashMap<>();
不建议这样:HashMap<String, Object> element= new HashMap<>();
第一种更灵活,第二种直接写死了,如果换其他的Map实现类,需要重写 ,如果是用接口实现 (第一种)只需要替换后面的实现类即可。
注释2:
containsKey方法——判断是否包含指定的键名
map是一个key和value的键值对的集合。有key和value键值对,就会有判断是否有key。这方法就是containsKey方法。
如果Map集合中包含指定的键名,则返回true,否则返回false。
语法 containsKey(Object key)