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

题目:

题解:

Go 复制代码
type node struct {
    keys  map[string]struct{}
    count int
}

type AllOne struct {
    *list.List
    nodes 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 仅出现一次,将其移出 nodes
        delete(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 ""
}
相关推荐
(●—●)橘子……11 分钟前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
FungLeo13 分钟前
成为全栈·Go 后端篇·重写之前先锁基线:契约、Node 版本与行为清单
golang·node.js·go·openapi·契约测试·成为全栈
wenyq736 分钟前
LeetCode 152. Maximum Product Subarray
java·算法·leetcode
念何架构之路1 小时前
OpenTelemetry核心概念
后端·目标跟踪·golang·c#·linq
紧跟先前的步伐1 小时前
Go AI Agent 实战 20|接入 DeepSeek 原生 Tool Calling
人工智能·ai·golang·1024程序员节
文丑颜不良啊1 小时前
LeetCode1181~1200题目解析
java·leetcode
海绵宝宝转agent2 小时前
Leetcode100+面经
java·笔记·学习·算法·leetcode·深度优先
紧跟先前的步伐2 小时前
# Go AI Agent 实战 21|多工具选择、参数校验与工具执行安全
人工智能·ai·golang