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 ""
}
相关推荐
Aurora20051 小时前
二叉树最小深度
算法·leetcode·职场和发展
雪的期许1 小时前
go结构体默认值和校验器(go-defaults、go-validator)
开发语言·后端·golang
心外无物的工作技术笔记1 小时前
【Go语言基础——一个Go语言项目典型的文件结构示例】
开发语言·笔记·golang·go
IronmanJay1 小时前
【LeetCode每日一题】——LCP 51.烹饪料理
数据结构·算法·leetcode·回溯·数组·递归·lcp 51.烹饪料理
walkskyer4 小时前
Golang plugin包教程:创建与管理插
golang
霍霍哈嗨4 小时前
【基础算法总结】分治--快排+归并
开发语言·算法·leetcode
DdddJMs__1355 小时前
C语言 | Leetcode C语言题解之第432题全O(1)的数据结构
c语言·leetcode·题解
spiker_6 小时前
用 Go 和 Redis 构建一个简单的任务管理系统
开发语言·redis·golang
码农小苏247 小时前
力扣刷题--476. 数字的补数【简单】
数据结构·算法·leetcode