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 ""
}
相关推荐
玖玥拾5 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
Awna6 小时前
Golang 大小写可见性规范
开发语言·后端·golang
Hi李耶6 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
进击的程序猿~9 小时前
Go 内存分配与垃圾回收源码深度学习手册
开发语言·后端·golang
geovindu10 小时前
go:Bit Operation Algorithm
开发语言·后端·算法·golang·位运算法
白白白小纯11 小时前
每日算法day3—回文链表,链表分割
c语言·数据结构·算法·leetcode
zander25812 小时前
35. 搜索插入位置:从边界语义理解二分查找
数据结构·算法·leetcode
yyds_yyd_1008613 小时前
3731. 找出缺失的元素(2026.08.04)
c++·leetcode
lueluelue4721 小时前
LeetCode:链表
算法·leetcode·链表