哈希实现
Arrays are amazing for looking up elements at specific indices as all elements in memory are contiguous, allowing for O(1)
or constant time lookups. But often we don't, or can't, perform lookups via indices. Hash maps and hash tables are a way around this, enabling us to lookup via keys
instead.
数组非常适合在特定索引处查找元素,因为内存中的所有元素都是连续的,允许进行O(1)
或恒定时间的查找。 但是,我们经常不通过索引进行查找,或者不能通过索引进行查找。 哈希映射和哈希表是解决此问题的一种方法,使我们能够通过keys
进行查找。
Can you implement the Map
class from scratch? Only two methods are necessary-- get
and set
. Many programming languages have a built-in hash or dictionary primitive (like Javascript
Object
s and {}
notation), but we don't want to use that for this exercise.
您可以从头开始实现Map
类吗? 仅需要两种方法get
和set
。 许多编程语言都有内置的哈希或字典原语(例如Javascript
Object
和{}
表示法),但是我们不想在本练习中使用它。
This lesson was originally published at https://algodaily.com, where I maintain a technical interview course and write think-pieces for ambitious developers.
本课程最初在 https://algodaily.com上 发布 ,我 在 那里维护技术面试课程,并为雄心勃勃的开发人员撰写思想著作。
Note: Regular Javascript
objects and the Map
class are both simple key-value hash tables/associative arrays, with a few key differences:
注意:常规Javascript
对象和Map
类都是简单的键值哈希表/关联数组,但有一些关键区别:
A Map
object can iterate through its elements in insertion order, whereas JavaScript's Object
s don't guarantee order. In addition, Object
s have default keys due to their prototype, and Map
s don't come with default keys. Here's a good breakdown of the two. For the purpose of this exercise, let's assume the same functionality for both.
一个 Map
对象可通过其插入顺序的元素迭代,而JavaScript的 Object
,说自己是为了保证。 另外, 由于 Object
的原型 ,