LeetCode 706 Design HashMap 解题报告

题目要求

Design a HashMap without using any built-in hash table libraries.

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.
  • get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
  • remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.

题目分析及思路

要求不使用任何内置的hash table库设计一个HashMap。具体要求是:1)put函数能将一对(key, value)插入到HashMap,若已经有value,则进行更新;2)get函数能获得对应key的value,若不存在key,则返回-1;3)remove函数能在key存在的时候去除key以及key对应的value。可以将key和value分别设置为列表,put函数里对key的存在性先进行判断,然后确定添加还是更新。get和remove函数同样需要对key的存在性先进行判断,然后前者获取对应key的索引,后者将key和与key同位置的value一起去掉。

python代码 

class MyHashMap:

    def __init__(self):

        """

        Initialize your data structure here.

        """

        self.keys = []

        self.vals = []

        

    def put(self, key: int, value: int) -> None:

        """

        value will always be non-negative.

        """

        if key not in self.keys:

            self.keys.append(key)

            self.vals.append(value)

        else:

            self.vals[self.keys.index(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

        """

        if key in self.keys:

            return self.vals[self.keys.index(key)]

        else:

            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

        """

        if key in self.keys:

            idx = self.keys.index(key)

            self.keys.remove(key)

            self.vals.pop(idx)

        

# Your MyHashMap object will be instantiated and called as such:

# obj = MyHashMap()

# obj.put(key,value)

# param_2 = obj.get(key)

# obj.remove(key)

 

posted on 2019-03-22 09:55  锋上磬音  阅读(124)  评论(0编辑  收藏  举报