2.7 哈希表

什么是哈希表

散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。

给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash) 函数。

哈希表的核心思想

​ 哈希表的设计采用了函数映射的思想,将记录的存储位置与记录的关键字关联起来。这样的设计方式,能够快速定位到想要查找的记录,而且不需要与表中存在的记录的关键字比较后再来进行查找。

例题

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

import java.util.HashMap;

public class HashTest {

	public static void main(String[] args) {
		int nums[] = { 2, 7, 11, 15 };
		
		int indexs[] = twoSum(nums, 9);
		
		for (int i = 0; i < indexs.length; i++) {
			System.out.print(indexs[i]+" ");

		}

	}

	public static int[] twoSum(int[] nums, int target) {

		int indexs[] = new int[2];

		HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

		for (int i = 0; i < nums.length; i++) {

			//k中有值表示符合条件
			if (hashMap.containsKey(nums[i])) {
				indexs[0] = hashMap.get(nums[i]);
				indexs[1] = i;
				return indexs;
			}

			//将值作为k ,index 作为 v
			hashMap.put(target - nums[i], i);
		}

		return indexs;
	}

}

posted @ 2020-10-24 15:53  Nixon  阅读(78)  评论(0编辑  收藏  举报