Design a data structure that supports all following operations in average O(1) time.

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection(); // Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1); // Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1); // Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2); // getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom(); // Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1); // getRandom should return 1 and 2 both equally likely.
collection.getRandom();

380. Insert Delete GetRandom O(1)的拓展,这题是可以有重复数字。只需将上一题目的解法稍作改动,依然使用哈希表+数组,这次哈希表中的值是保存数组下标的一个Set。

Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.TreeSet; public class RandomizedCollection { private HashMap<Integer, TreeSet<Integer>> dataMap;
private ArrayList<Integer> dataList;
/** Initialize your data structure here. */
public RandomizedCollection() {
dataMap = new HashMap<Integer, TreeSet<Integer>>();
dataList = new ArrayList<Integer>();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
TreeSet<Integer> idxSet = dataMap.get(val);
if (idxSet == null) {
idxSet = new TreeSet<Integer>();
dataMap.put(val, idxSet);
}
idxSet.add(dataList.size());
dataList.add(val);
return idxSet.size() == 1;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
TreeSet<Integer> idxSet = dataMap.get(val);
if (idxSet == null || idxSet.isEmpty()) {
return false;
}
int idx = idxSet.pollLast(); //Last index of val
int tail = dataList.get(dataList.size() - 1); //Tail of list
TreeSet<Integer> tailIdxSet = dataMap.get(tail);
if (tail != val) {
tailIdxSet.pollLast(); //Remove last idx of list tail
tailIdxSet.add(idx); //Add idx to tail idx set
dataList.set(idx, tail);
}
dataList.remove(dataList.size() - 1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return dataList.get(new Random().nextInt(dataList.size()));
}
}

Python:

from random import randint
from collections import defaultdict class RandomizedCollection(object): def __init__(self):
"""
Initialize your data structure here.
"""
self.__list = []
self.__used = defaultdict(list) def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
has = val in self.__used self.__list += val,
self.__used[val] += len(self.__list)-1, return not has def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.__used:
return False self.__used[self.__list[-1]][-1] = self.__used[val][-1]
self.__list[self.__used[val][-1]], self.__list[-1] = self.__list[-1], self.__list[self.__used[val][-1]] self.__used[val].pop()
if not self.__used[val]:
self.__used.pop(val)
self.__list.pop() return True def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
return self.__list[randint(0, len(self.__list)-1)]

C++:

class RandomizedCollection {
public:
/** Initialize your data structure here. */
RandomizedCollection() {} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
m[val].insert(nums.size());
nums.push_back(val);
return m[val].size() == 1;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if (m[val].empty()) return false;
int idx = *m[val].begin();
m[val].erase(idx);
if (nums.size() - 1 != idx) {
int t = nums.back();
nums[idx] = t;
m[t].erase(nums.size() - 1);
m[t].insert(idx);
}
nums.pop_back();
return true;
} /** Get a random element from the collection. */
int getRandom() {
return nums[rand() % nums.size()];
} private:
vector<int> nums;
unordered_map<int, unordered_set<int>> m;
};

  

类似题目:

[LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间

All LeetCode Questions List 题目汇总

[LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复的更多相关文章

  1. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  2. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. Note: Duplic ...

  3. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  4. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed

    原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...

  5. LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed (插入删除和获得随机数 常数时间 允许重复项)

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  6. [leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  7. leetcode 380. Insert Delete GetRandom O(1) 、381. Insert Delete GetRandom O(1) - Duplicates allowed

    380. Insert Delete GetRandom O(1) 实现插入.删除.获得随机数功能,且时间复杂度都在O(1).实际上在插入.删除两个功能中都包含了查找功能,当然查找也必须是O(1). ...

  8. 381. Insert Delete GetRandom O(1) - Duplicates allowed

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  9. [LeetCode] Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

随机推荐

  1. Sql操作时间

    --. 当前系统日期.时间 -- ::27.277 --.时间操作 dateadd 在向指定日期加上一段时间的基础上,返回新的 datetime 值 dateadd(datepart,number,d ...

  2. postgres —— 窗口函数入门

    注:测试数据在 postgres —— 分组集与部分聚集 中 聚集将多行转变成较少.聚集的行.而窗口则不同,它把当前行与分组中的所有行对比,并且返回的行数没有变化. 组合当前行与 production ...

  3. 1.zookeeper是干什么的?

    Zookeeper是Hadoop的一个子项目,虽然源自hadoop,但是我发现zookeeper脱离hadoop的范畴开发分布式框架的运用越来越多.今天我想谈谈zookeeper,本文不谈如何使用zo ...

  4. python的zip()函数

    zip() 函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象. 如果各个可迭代对象的元素个数不一致,则返回的对象长度与最短的可迭代对象相同. 利用 * 号 ...

  5. Centos7安装Spark2.4

    准备 1.hadoop已部署(若没有可以参考:Centos7安装Hadoop2.7),集群情况如下(IP地址与之前文章有变动): hostname IP地址 部署规划 node1 172.20.0.2 ...

  6. webuploader解决大文件断点续传

    文件夹数据库处理逻辑 public class DbFolder { JSONObject root; public DbFolder() { this.root = new JSONObject() ...

  7. 微信浏览器中清缓存的方法---- http://debugx5.qq.com/

    http://debugx5.qq.com/ 点击上面网址,然后把底部的四个选项打钩,然后点清除,即可把可恶的缓存清掉!!!!!

  8. 【cf contest 1119 H】Triple

    题目 给出 \(n\) 个三元组\(\{ a_i,b_i,c_i \}\)和\(x,y,z\): 将每个三元组扩展成(\(x\)个\(a_i\),\(y\)个\(b_i\),\(z\)个\(c_i\) ...

  9. 1.typescirpt学习之路,*.d.ts和@types关系理解

    今天看了看ts,文档上很多没用讲,小编疑惑了很久一个问题! *.d.ts和@types啥关系,小编查阅了很多文档,才弄明白. 首先,@types是npm的一个分支,我们把npm包发上去,npm包就会托 ...

  10. HTML5之contenteditable可编辑属性

    运用contenteditable实现输入框高度自动增加,输入框标题name相对高度自动居中,代码如下: <!DOCTYPE html> <html> <head> ...