[LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.remove(val): Removes an item val from the collection if present.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)时间 - 允许重复的更多相关文章
- [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- 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 ...
- [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 ...
- LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed
原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...
- 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 ...
- [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 ...
- 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). ...
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- [LeetCode] Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
随机推荐
- 【Herding HDU - 4709 】【数学(利用叉乘计算三角形面积)】
题意:给出n个点的坐标,问取出其中任意点围成的区域的最小值! 很明显,找到一个合适的三角形即可. #include<iostream> #include<cstdio> #in ...
- 倍增法求lca(最近公共祖先)
倍增法求lca(最近公共祖先) 基本上每篇博客都会有参考文章,一是弥补不足,二是这本身也是我学习过程中找到的觉得好的资料 思路: 大致上算法的思路是这样发展来的. 想到求两个结点的最小公共祖先,我们可 ...
- Improving Sequential Recommendation with Knowledge-Enhanced Memory Networks(知识图谱)
本文作者:杨昆霖,2015级本科生,目前研究方向为知识图谱,推荐系统,来自中国人民大学大数据管理与分析方法研究北京市重点实验室. 引言 经常上购物网站时,注意力会被首页上的推荐吸引过去,往往本来只想买 ...
- C# 退出应用程序的几种方法
Application.Exit();//好像只在主线程可以起作用,而且当有线程,或是阻塞方法的情况下,很容易失灵 this.Close();//只是关闭当前窗体. Application.ExitT ...
- Navicat 的使用 —— 快捷键
名称 功能 备注 Ctrl+Q 打开查询窗口 Ctrl+/ 注释sql语句 Ctrl+R 运行查询窗口的sql语句 Ctrl+Shift+R 只运行选中的sql语句 F6 打开一 ...
- template_constructor_function
#include <iostream> using namespace std; template <class T> class MyClass{ public: templ ...
- LeetCode(数据库)部门最高工资
), Salary int, DepartmentId int) )) Truncate table Employee ') ') ') ') Truncate table Department ', ...
- BBS总结 --- django设计
目录 1.调用模块使用 2.BBS中urls.py 3.django中配置 4.新学方法使用 5.BBS用到的知识点 1.调用模块使用 from django.db import models fro ...
- LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters
原题链接在这里:https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters ...
- hibernate之多对多关系
hibernate的多对多hibernate可以直接映射多对多关联关系(看作两个一对多) 下面我们拿三张表来做实例 t_book_hb t_book_category_hb(桥接表) t_catego ...