您的位置:首页 > 其它

算法:哈希表理论知识

2017-11-16 15:51 148 查看

一、哈希表

1.定义

  散列表(Hash table,也叫哈希表),是根据键(Key)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做散列表

2.基础概念

1>若关键字为k,则其值存放在f(k)的存储位置上。由此,不需比较便可直接取得所查记录。称这个对应关系f散列函数,按这个思想建立的表为散列表

2>对不同的关键字可能得到同一散列地址,即k1 != k2,而 f(k1) = f(k2),这种现象称为冲突(英语:Collision)。具有相同函数值的关键字对该散列函数来说称做同义词

3>若对于关键字集合中的任一个关键字,经散列函数映象到地址集合中任何一个地址的概率是相等的,则称此类散列函数为均匀散列函数(Uniform Hash function),这就是使关键字经过散列函数得到一个“随机的地址”,从而减少冲突。

二、算法使用哈希

1.题目描述

Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,

s = “anagram”, t = “nagaram”, return true.

s = “rat”, t = “car”, return false.

Note:

You may assume the string contains only lowercase alphabets.

2.使用哈希表思想来解决

Algorithm

To examine if tt is a rearrangement of ss, we can count occurrences of each letter in the two strings and compare them. Since both ss and tt contain only letters from a-za−z, a simple counter table of size 26 is suffice.

Do we need two counter tables for comparison? Actually no, because we could increment the counter for each letter in ss and decrement the counter for each letter in tt, then check if the counter reaches back to zero.

/**
* 判断字符串s和t是否为回文构词法
* @param s
* @param t
* @return
*/
public static boolean isAnagram(String s, String t) {
//特殊情况处理
if (s.length() != t.length())
return false;

int[] counter = new int[26];

//通过散列函数f(k) = k - 'a',将字符k 映射到counter数组上
for(int i = 0; i < s.length(); i++){
counter[s.charAt(i) - 'a']++;
counter[t.charAt(i) - 'a']--;
}

for (int count : counter){
if (count != 0)
return false;
}

return true;
}


额外说明:

这个判断回文构词法算法中:键是字符 k,且字符k 的取值范围是 [‘a’,’z’],散列函数f(k) = k -‘a’。则f(k)值域为[0,25];所以可以使用int[] counter = new int[26]; 一个大小为26的数组作为散列表。

扩充:

此处散列方法是直接定址法:取关键字或关键字的某个线性函数值为散列地址。即 f(k)=a * k + b,其中 a, b均为常数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息