【leetcode】哈希表相关高频题目整理

100 阅读1分钟

哈希

kv映射,时间复杂度O(1),空间复杂度O(n)。

  • 【1】两数之和:哈希记录值和下标

  • 【146】LRU:哈希+双向链表

    • get,输出m[key],更新m[key]到链表头

    • Put:

      • key存在则更新并刷新
      • 不存在,满了就删除链表尾,创建m[key]放到链表头
    • type LRUCache struct {
          size int
          m map[int]*Node
          head *Node
          tail *Node
      }
      
      type Node struct{
          key int
          value int
          l *Node
          r *Node
      }
      
      func Constructor(capacity int) LRUCache {
          head,tail:=&Node{},&Node{}
          head.r,tail.l = tail,head
          return LRUCache{capacity,map[int]*Node{},head,tail}
      }
      
      func (this *LRUCache) Get(key int) int {
          if node,ok:=this.m[key];ok{
              this.flush(key)
              return node.value
          }
          return -1
      }
      
      func (this *LRUCache) flush(key int)  {
          node:=this.m[key]
          node.l.r,node.r.l = node.r,node.l
          node.r,node.l,this.head.r,this.head.r.l = this.head.r,this.head,node,node
      }
      
      func (this *LRUCache) del()  {
          node:=this.tail.l
          this.tail.l,node.l.r = node.l,this.tail
          delete(this.m, node.key)
      }
      
      func (this *LRUCache) Put(key int, value int)  {
          if node,ok:=this.m[key];ok{
              node.value = value
              this.flush(key)
          }else{
              if this.size == len(this.m){
                  this.del()
              }
              newNode:=&Node{key,value,this.head,this.head.r}
              this.head.r,newNode.r.l = newNode,newNode
              this.m[key]= newNode
          }
      }
      
  • 【128】最长连续序列:所有数存入hash,枚举每一个数,看这个数是不是连续序列的起点(num-1是不是存在),是起点就枚举看这个区间的长度。

  • 【347】前 K 个高频元素:所有元素存入hash,记录len,像俄罗斯方块一样,所有v都减1,最后剩下k个就是这些中最大的

  • 【380】O(1) 时间插入、删除和获取随机元素:hash+数组

  • 【454】四数相加 II:hash存储前两个数组和以及对应数目,枚举后两个数组的和在hash里查找

  • 【974】和可被 K 整除的子数组:map记录前缀和对k取模的数量,ans += m[(tmp%k+k)%k]