Skip to content

Commit

Permalink
vault backup: 2023-12-10 16:35:33
Browse files Browse the repository at this point in the history
Affected files:
docs/01数据结构与算法/04哈希表.md
  • Loading branch information
givedrug committed Dec 10, 2023
1 parent a3e9808 commit 3c4504c
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions docs/01数据结构与算法/04哈希表.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
这里以取整函数作为哈希函数,并使用链地址法来实现一个简易的HashSet:

```java

class MyHashSet {
private static final int BASE = 769;
private LinkedList[] data;
Expand Down Expand Up @@ -69,7 +68,6 @@ class MyHashSet {
return key % BASE;
}
}

```

- 时间复杂度:$O(\frac{n}{b})$ 其中 $n$ 是元素个数, $b$ 是链表节点个数
Expand All @@ -85,15 +83,18 @@ class MyHashSet {
在初等数学中有一个基本定理,任意一个大于1的自然数,要么本身就是质数,要么可以分解为几个质数之积,这种分解本身,具有唯一性。

数字的因子越多,取模后冲突的可能性就越大。而素数的因子恰好只有1和其本身,就非常适合用于解决冲突。

比如2,4,6,8,10,12这6个数

如果对6取余,得到2,4,0,2,4,0只会得到3种HASH值,6的因子有1,2,3,6。冲突会很多。

如果对7取余,得到2,4,6,1,3,5得到6种HASH值,而7的因子只有1,7。

(即使1的因子最小,但是在实际中并不用,因为mod1相当于不解决冲突。而初始化的的数组就会非常大。)

Hash的用途很多,我们在使用Ngnix做负载均衡的时候,同样用的也是Hash的方式。总的来说,要是数据分布均匀一些,在这种时候就可以考虑使用Hash的方式对数据进行处理。

参考:
1. [leetcode题解]( https://leetcode.cn/problems/design-hashset/solutions/)
参考:[leetcode题解]( https://leetcode.cn/problems/design-hashset/solutions/)

### HashMap设计

Expand Down

0 comments on commit 3c4504c

Please sign in to comment.