This is my first day at 365 days of coding challenge. I will try solving the most frequently asked questions in interviews from leetcode. The motive behind writing medium post is two-fold,
这是我参加365天编码挑战的第一天。 我将尝试在leetcode的访谈中解决最常见的问题。 撰写中等职位的动机是双重的,
a. The article will remain with me and I would be able to revise whenever needed.
一种。 该文章将保留在我身上,我将能够在需要时进行修改。
b. Hopefully, you will be able to understand the solution and would be able to implement them with ease.
b。 希望您能够理解该解决方案,并能够轻松实现它们。
Without wasting much of the time, Let's jump into the question.
在不浪费大量时间的情况下,让我们跳入这个问题。
706. Design HashMap
706 。 设计HashMap
Design a HashMap without using any built-in hash table libraries.
在不使用任何内置哈希表库的情况下设计HashMap。
To be specific, your design should include these functions:
具体来说,您的设计应包括以下功能:
put(key, value)
: Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.
put(key, value)
:将(key,value)对插入HashMap中。 如果HashMap中已经存在该值,请更新该值。get(key)
: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
get(key)
:返回指定键所映射到的值;如果此映射不包含该键的映射,则返回-1。remove(key)
: Remove the mapping for the value key if this map contains the mapping for the key.
remove(key)
:如果此值包含键的映射,则删除值键的映射。
Example:
例:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // returns 1
hashMap.get(3); // returns -1 (not found)
hashMap.put(2, 1); // update the existing value
hashMap.get(2); // returns 1
hashMap.remove(2); // remove the mapping for 2
hashMap.get(2); // returns -1 (not found)
Notes:
笔记:
- All keys and values will be in the range of
[0, 1000000]
.
所有键和值都将在[0, 1000000]
范围内。 - The number of operations will be in the range of
[1, 10000]
.
操作数将在[1, 10000]
范围内。 - Please do not use the built-in HashMap library.
What are the features of a HashMap?
HashMap的功能是什么?
- It has a key that uniquely identifies the record.
- Each key will have a value, which can be a string, int, list, set, etc, or a mix of everything.
Solution 1:
解决方案1:
All the keys in the given question will be int and in range of [0, 1000000].
给定问题中的所有键均为int,且范围为[ 0, 1000000].
We can initialize an array of size 1000000
with values as -1.
我们可以使用值为-1初始化大小为1000000
的数组。
Whenever we get a new value for the key we can insert in the respective index of the array.
每当我们获得键的新值时,我们都可以将其插入数组的相应索引中。
We can return/update whatever value is present for in that index(given key) at any point.
我们可以随时返回/更新该索引(给定键)中存在的任何值。
Please find the implementation as below
请找到以下实现
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.my_array = [-1 for i in range(1000000)] def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
self.my_array[key] = value
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
return self.my_array[key] def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
self.my_array[key] = -1
Complexity analysis
复杂度分析
Time Complexity
时间复杂度
To put the key in the array → O(1)
将密钥放入数组→ O(1)
To get the key from the array → O(1)
要从数组中获取密钥→ O(1)
Space Complexity
空间复杂度
The space required is of size O(N) where N is the max value that can be present in the hashmap. In our case, it is O(1000000)
所需空间的大小为O(N),其中N是哈希图中可以存在的最大值。 在我们的例子中是O(1000000)
The above can be also implemented as a 2-D array.
以上也可以实现为二维阵列。
Consider having 1000 rows and 1000 columns initialized as -1. When we get a new key the row number will be key divided by 1000 while the column will be its remainder. Complexity still remains the same since we are initializing the 2-D array.
考虑将1000行和1000列初始化为-1。 当我们得到一个新的键时,行号将被键除以1000,而列将是其剩余部分。 由于我们正在初始化二维数组,因此复杂度仍然保持不变。
One issue with the above logic is we tend to waste a lot of space. We might have only 3 elements in our hashmap, but we initialized the entire range, which will lead to wastage of space.
上述逻辑的一个问题是我们倾向于浪费大量空间。 我们的哈希图中可能只有3个元素,但是我们初始化了整个范围,这将导致空间浪费。
How can we improve the solution to make better utilization of space?
我们如何改善解决方案以更好地利用空间?
Maybe we can come up with some kind of hashing function which will give us better utilization of space.
也许我们可以提出某种哈希函数,这将使我们更好地利用空间。
We can try modifying the logic of using the 2-D array for better utilization of space.
我们可以尝试修改使用二维数组的逻辑,以更好地利用空间。
Solution:
解:
- Initialize an array of size 1000(we are taking 1000 here as that was the number of rows when we were using 2-D array logic).
- Fill that array with -1.
- In the put function, we will be using our hashing logic to find the right address. In our case, we are finding the modulus given by 1000. This number will be our index in whose bucket we will be inserting our value
- Check if any buckets are created in this location(above obtained key). If not initialize a list with another list of key, value.
- If there is a bucket already present above location, iteratively check if the key is already present if yes then update with new value else append at the end of the list.
- For the remove function, Find the modulus, check if the bucket is present, If the bucket is present, then iteratively check for the key if the key is present then remove that element from the bucket else do nothing.
class MyHashMap: def __init__(self):
"""
Initialize your data structure here.
"""
self.num_bucket = 1000
self.buckets = [-1] * self.num_bucket
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
ind = key%self.num_bucket
#print("put hashmap",self.buckets[ind])
if self.buckets[ind] == -1:
self.buckets[ind] = [[key, value]]
return
for index, kv in enumerate(self.buckets[ind]):
if kv[0] == key:
self.buckets[ind][index][1] = value
return
self.buckets[ind].append([key,value])
return
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
ind = key%self.num_bucket
#print("get hashmap",self.buckets[ind])
if self.buckets[ind] == -1:
return -1
for k, v in self.buckets[ind]:
if k == key:
return v
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
#print("remove hashmap",self.buckets)
ind = key % self.num_bucket
ind_to_remove = -1
if self.buckets[ind] == -1:
return
for i, kv_pair in enumerate(self.buckets[ind]):
if kv_pair[0] == key:
ind_to_remove = i
break
if ind_to_remove == -1:
return
else:
del self.buckets[ind][ind_to_remove]
Complexity analysis
复杂度分析
Time Complexity
时间复杂度
The overall time complexity for each function will be O(N/1000) where N is the number of keys that are possible.
每个功能的总时间复杂度将为O(N / 1000),其中N是可能的键数。
Space Complexity
空间复杂度
The space required is of size O(1000 + M) where M is the key that we have
所需空间的大小为O(1000 + M),其中M是我们拥有的密钥
I would like to improve my writing skills so any suggestions or critiques are highly welcomed.
我想提高自己的写作技巧,因此任何建议或批评都将受到欢迎。