4 篇文章 0 订阅

1 Hash Function

(1) it always returns a number for an object

(2) two equal objects will always have the same number

(3) two unequal objects not always have different numbers

One way to implement in Java is hashCode(). The hashCode() method is implemented in the Oject class and therefore each class in Java inherits it. The hash code provides a numeric representation of an object.(somewhat similar to toString method that gives a text representation of an object)

2 Collision & Rehash Question from lintcode

Collision : different objects( by equals() method) may have same hashcode.

2 way to solve collision:

(1) Separate chaining sollision resolution: use linked list ---- hashtable is an array of list

(2) Linear probing:  if can not insert at index k, try next slot k + 1.if occupied, go to k + 2.

Rehash question from lintcode

The size of the hash table is not determinate at the very beginning. If the total size of keys is too large (e.g. size >= capacity / 10), we should double the size of the hash table and rehash every keys. Say you have a hash table looks like below:

size=3, capacity=4
[null, 21->9->null, 14->null, null]

The hash function is:

int hashcode(int key, int capacity) {
return key % capacity;
}

here we have three numbers, 9, 14 and 21, where 21 and 9 share the same position as they all have the same hashcode 1 (21 % 4 = 9 % 4 = 1). We store them in the hash table by linked list.rehashing this hash table, double the capacity, you will get:

size=3, capacity=8
index: 0 1 2 3 4 5 6 7
hash table: [null, 9, null, null, null, 21, 14, null]

Given the original hash table, return the new hash table after rehashing .
Note
For negative integer in hash table, the position can be calculated as follow:

In C++/Java, if you directly calculate -4 % 3 you will get -1. You can use function: a % b = (a % b + b) % b to make it is a non negative integer.

In Python, you can directly use -1 % 3, you will get 2 automatically.

Example
Given [null, 21->9->null, 14->null, null], return [null, 9->null, null, null, null, 21->null, 14->null, null]

hashtable is constant time performance for add, remove, contains, size.

collision : worst all collide into same index,  need to search for one of them == search in list (linear time)

How to guarantee expected constant time?

make sure lists not become too long. Usually implemented by Load Factor.

Load factor keeps track of average length of lists, if approaches a set in advanced threshold, create a bigger array and rehash all elements from old table into a new one.

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
04-30
11-23 180
04-01 74
03-10 2901
02-23 1万+
04-15 2653
08-09 386

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

xiaomaolearnCoding

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。