380. O(1) 时间插入、删除和获取随机元素
O(1) 时间插入、删除和获取随机元素
题目描述:
实现RandomizedSet 类:
RandomizedSet() 初始化 RandomizedSet 对象
bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。
bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。
int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。
示例:
输入
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]
解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
提示:
-231 <= val <= 231 - 1
最多调用 insert、remove 和 getRandom 函数 2 * 105 次
在调用 getRandom 方法时,数据结构中 至少存在一个 元素。
思路:
时间复杂度:O(1),空间复杂度O(1)
使用hash和arr做,创建一个5*10000的arr,重点是删除操作,删除了target数之后最后一个数填进删除的target的idx中。
代码:
type RandomizedSet struct {
nums [200000]int
mp map[int]int
idx int
}
func Constructor() RandomizedSet {
randomizedSet := new(RandomizedSet)
randomizedSet.mp = make(map[int]int,0)
return *randomizedSet
}
func (this *RandomizedSet) Insert(val int) bool {
if _,ok := this.mp[val];ok{
return false
}else{
this.nums[this.idx] = val
this.mp[val] = this.idx
this.idx++
}
return true
}
func (this *RandomizedSet) Remove(val int) bool {
if _,ok := this.mp[val];!ok{
return false
}else{
i := this.mp[val]
this.mp[this.nums[this.idx-1]] = i
this.nums[i] = this.nums[this.idx-1]
this.idx--
delete(this.mp,val)
}
return true
}
func (this *RandomizedSet) GetRandom() int {
i := rand.Intn(this.idx)
return this.nums[i]
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Insert(val);
* param_2 := obj.Remove(val);
* param_3 := obj.GetRandom();
*/
代码效率:
执行用时:152 ms, 在所有 Go 提交中击败了41.21%的用户
内存消耗:59.8 MB, 在所有 Go 提交中击败了5.24%的用户
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!