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 ""
}
相关推荐
楼田莉子1 小时前
C++算法学习专题:前缀和
c++·学习·算法·leetcode·蓝桥杯
HalvmånEver2 小时前
盛最多水的容器:双指针法的巧妙运用(leetcode 11)
c++·学习·leetcode
CaracalTiger5 小时前
网站漏洞早发现:cpolar+Web-Check安全扫描组合解决方案
java·开发语言·前端·python·安全·golang·wpf
YSRM6 小时前
Leetcode+Java+动态规划IV
java·leetcode·动态规划
YoungHong199213 小时前
面试经典150题[019]:最后一个单词的长度(LeetCode 58)
leetcode·面试·职场和发展
完美世界的一天16 小时前
Golang 面试题「中级」
开发语言·后端·面试·golang
逢生博客18 小时前
使用 SmartIDE 开发长安链 Go 语言智能合约
golang·web3·区块链·智能合约·长安链
圣保罗的大教堂21 小时前
leetcode 3446. 按对角线进行矩阵排序 中等
leetcode
Swift社区1 天前
Swift 解法详解:LeetCode 367《有效的完全平方数》
开发语言·leetcode·swift
完美世界的一天1 天前
Golang 面试题「初级」
开发语言·面试·golang