• 力扣706-设计哈希映射


    原题 :https://leetcode-cn.com/problems/design-hashmap/

    不使用任何内建的哈希表库设计一个哈希映射(HashMap)。

    实现 MyHashMap 类:

      MyHashMap() 用空映射初始化对象 void put(int key, int value) 向 HashMap 插入一个键值对 (key, value) 。

      如果 key 已经存在于映射中,则更新其对应的值 value 。 int get(int key) 返回特定的 key 所映射的 value ;

      如果映射中不包含 key 的映射,返回 -1 。 void remove(key) 如果映射中存在 key 的映射,则移除 key 和它所对应的 value 。

    个人理解

      对于哈希表,在数据结构可以用一个数组加链表的组合,数组为了可以对数据分组,

      可以加快查询速度,对于在同一个组内的数据进行遍历就可以找到数据的了

    class MyHashMap:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.buckets = 1009
            self.table = [ [] for _ in range(self.buckets) ]
    
        def hash(self,key):
            return key % self.buckets        
    
    
        def put(self, key: int, value: int) -> None:
            """
            value will always be non-negative.
            """
            hashkey = self.hash(key)
            for item in  self.table[hashkey]:
                if item[0] == key:
                    item[1] = value
                    return
            self.table[hashkey].append([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
            """
            hashkey = self.hash(key)
            for item in self.table[hashkey]:
                if item[0] == key:
                    return item[1]
            return -1
    
        def remove(self, key: int) -> None:
            hashkey = self.hash(key)
            for i, item in enumerate(self.table[hashkey]):
                if item[0] == key:
                    self.table[hashkey].pop(i)
                    return
  • 相关阅读:
    HDU 1402 A * B Problem Plus FFT
    HDU 4609 3-idiots FFT
    Hihocoder #1527 : 快速乘法 DP
    Codeforces Round #420 (Div. 2) E. Okabe and El Psy Kongroo DP+矩阵快速幂加速
    Codeforces 8VC Venture Cup 2016
    FFT做题记录
    Hackrank Candies DP
    git submodule update --init --recursive
    慢慢长大
    protobuf
  • 原文地址:https://www.cnblogs.com/wang102030/p/14533987.html
Copyright © 2020-2023  润新知