哈希表在Java中的使用
定义
对象的存储位置和对象的关健值之间存在某种对应关系。其定义同数据结构之中的定义。
在java中的使用
-
导包
import java.util.HashMap; -
定义
HsahMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); //参数定义使用的是基本类型的包装类 -
常见用法
(1)hash.put(1,3); //在一位置存入对应的关键字
(2)hash.get(1); //获取一位置对应的关键字
(3)hash.containsKey(3) //用于判断某个关键字是否在哈希表中存在,返回值为true 或者false
参考代码
题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs = new int[2];
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
if(hash.containsKey(nums[i]))
{
indexs[0] = hash.get(nums[i]);
indexs[1] = i;
return indexs;
}
hash.put(target-nums[i],i);
}
return indexs;
}
}