当前位置: 首页 > news >正文

Golang | Leetcode Golang题解之第题432题全O(1)的数据结构

题目:

题解:

type node struct {keys  map[string]struct{}count int
}type AllOne struct {*list.Listnodes map[string]*list.Element
}func Constructor() AllOne {return AllOne{list.New(), map[string]*list.Element{}}
}func (l *AllOne) Inc(key string) {if cur := l.nodes[key]; cur != nil {curNode := cur.Value.(node)if nxt := cur.Next(); nxt == nil || nxt.Value.(node).count > curNode.count+1 {l.nodes[key] = l.InsertAfter(node{map[string]struct{}{key: {}}, curNode.count + 1}, cur)} else {nxt.Value.(node).keys[key] = struct{}{}l.nodes[key] = nxt}delete(curNode.keys, key)if len(curNode.keys) == 0 {l.Remove(cur)}} else { // key 不在链表中if l.Front() == nil || l.Front().Value.(node).count > 1 {l.nodes[key] = l.PushFront(node{map[string]struct{}{key: {}}, 1})} else {l.Front().Value.(node).keys[key] = struct{}{}l.nodes[key] = l.Front()}}
}func (l *AllOne) Dec(key string) {cur := l.nodes[key]curNode := cur.Value.(node)if curNode.count > 1 {if pre := cur.Prev(); pre == nil || pre.Value.(node).count < curNode.count-1 {l.nodes[key] = l.InsertBefore(node{map[string]struct{}{key: {}}, curNode.count - 1}, cur)} else {pre.Value.(node).keys[key] = struct{}{}l.nodes[key] = pre}} else { // key 仅出现一次,将其移出 nodesdelete(l.nodes, key)}delete(curNode.keys, key)if len(curNode.keys) == 0 {l.Remove(cur)}
}func (l *AllOne) GetMaxKey() string {if b := l.Back(); b != nil {for key := range b.Value.(node).keys {return key}}return ""
}func (l *AllOne) GetMinKey() string {if f := l.Front(); f != nil {for key := range f.Value.(node).keys {return key}}return ""
}

http://www.mrgr.cn/news/34747.html

相关文章:

  • Golang | Leetcode Golang题解之第433题最小基因变化
  • GNU链接器(LD):LMA、VMA等链接脚本基本概念
  • Excel 获取某列不为空的值【INDEX函数 | SMALL函数或 LARGE函数 | ROW函数 | ISBLANK 函数】
  • 2024在线翻译工具横评:准确率、速度与易用性大比拼
  • Java | Leetcode Java题解之第433题最小基因变化
  • Python | Leetcode Python题解之第433题最小基因变化
  • scss知识汇总
  • JS数组随机取数
  • Java运算符
  • centos7 docker部署nacos
  • 公安局党建平台建设方案和必要性-———未来之窗行业应用跨平台架构
  • 【我的 PWN 学习手札】fastbin reverse into tcache —— tcache key 绕过
  • 使用GLib进行C语言编程的实例
  • typename、非类型模板参数、模板参数的特化、模板类成员函数声明和定义分离、继承等的介绍
  • LED显示屏驱动电源:恒流与恒压,谁更胜一筹?
  • 在uboot中添加自定义命令
  • Robot Operating System——带有时间戳和坐标系信息的多边形信息
  • ubuntu内网穿透后在公网使用ssh登录
  • could not broadcast input array from shape
  • 盘点那些功能强大的思维导图在线工具,你用过几个