前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2021-11-10:O(1) 时间插入、删除和获取随机元素。实现RandomizedSet 类:RandomizedSet()

2021-11-10:O(1) 时间插入、删除和获取随机元素。实现RandomizedSet 类:RandomizedSet()

作者头像
福大大架构师每日一题
发布2021-11-16 10:32:41
2440
发布2021-11-16 10:32:41
举报
文章被收录于专栏:福大大架构师每日一题

2021-11-10:O(1) 时间插入、删除和获取随机元素。实现RandomizedSet 类:RandomizedSet() 初始化 RandomizedSet 对象。bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。力扣380。

答案2021-11-10:

两张哈希表。

v→index。

index→v。

index一定是连续的。

删除中间位置的元素,用最后一个元素顶替。这样index就连续了。

代码用golang编写。代码如下:

代码语言:javascript
复制
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())
    nrs := NewRandomizedSet()
    nrs.insert(6)
    nrs.insert(3)
    nrs.insert(7)
    nrs.insert(9)
    nrs.insert(8)
    fmt.Println(nrs.getRandom())
}

type RandomizedSet struct {
    keyIndexMap map[int]int
    indexKeyMap map[int]int
    size        int
}

func NewRandomizedSet() *RandomizedSet {
    res := &RandomizedSet{}
    res.keyIndexMap = make(map[int]int)
    res.indexKeyMap = make(map[int]int)
    res.size = 0
    return res
}

func (this *RandomizedSet) insert(val int) bool {
    if _, ok := this.keyIndexMap[val]; !ok {
        this.keyIndexMap[val] = this.size
        this.indexKeyMap[this.size] = val
        this.size++
        return true
    }
    return false
}

func (this *RandomizedSet) remove(val int) bool {
    if _, ok := this.keyIndexMap[val]; ok {
        deleteIndex := this.keyIndexMap[val]
        this.size--
        lastIndex := this.size
        lastKey := this.indexKeyMap[lastIndex]
        this.keyIndexMap[lastKey] = deleteIndex
        this.indexKeyMap[deleteIndex] = lastKey
        delete(this.keyIndexMap, val)
        delete(this.indexKeyMap, lastIndex)
        return true
    }
    return false
}

func (this *RandomizedSet) getRandom() int {
    if this.size == 0 {
        return -1
    }
    randomIndex := rand.Intn(this.size)
    return this.indexKeyMap[randomIndex]
}

执行结果如下:

[左神java代码](https://github.com/algorithmzuo/coding-for-great-offer/blob/main/src/class34/Problem_0380_InsertDeleteGetRandom.java)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-11-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 福大大架构师每日一题 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档