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. win10下无法安装loadrunner,提示“管理员已阻止你运行此应用”

    如下图: 1.再次进入控制面板,并且选择用户账户后把最下面的[更改用户账户控制设置],里面有个滑条,把滑条拉到最下面的[从不通知]上面并且确定. 2.按[Win+R]快捷键打开运行,输入 gpedit ...

  2. 关于srping的AOP事务管理问题,自定义切面是否导致事务控制失效

    applicationContext.xml: <!-- 方法调用时间记录 --> <bean id="methodExecuteTime" class=&quo ...

  3. java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

    java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more tha ...

  4. SpringMVC的全局异常处理

    @ControllerAdvice的使用 我们都知道做项目一般都会有全局异常统一处理的类,那么这个类在Spring中可以用@ControllerAdvice来实现. @ControllerAdvice ...

  5. $().on()的知识点

    事件冒泡阶段:事件从事件目标(target)开始,往上冒泡直到页面的最上一级标签. 假设一个元素div,它有一个下级元素p.<div> <p>元素</p></ ...

  6. 对生成对抗网络GANs原理、实现过程、应用场景的理解(附代码),另附:深度学习大神文章列表

    https://blog.csdn.net/love666666shen/article/details/75522489 https://blog.csdn.net/yangdelong/artic ...

  7. RSDS pdb格式

    本描述了“RSDS”或“DS”类型的pdb(程序数据库)文件的格式,这些文件是由Miscrosoft的link.exe从版本7及更高版本发出的. 什么是PDB文件? 如果选择了/DEBUG选项或/DE ...

  8. Prisma 2 is Coming Soon

    转自:https://www.prisma.io/blog/prisma-2-is-coming-soon-mwwfhevie993 Prisma 2 will introduce many fund ...

  9. go与python的不同

    go 开发中需要注意的与python的不同点 列出golang开发过程中与python的不同点,主要是在语法方面,golang的一些语法真是要人命啊. 1.golang可读性很强,与或对应&& ...

  10. x32下的DLL隐藏

    原理主要就是PEB 中模块断链. 这里整理下代码.原理可以看下另一篇我写的帖子. https://www.cnblogs.com/iBinary/p/9601860.html // dllmain.c ...