0%

leetcode Insert Delete GetRandom O(1) - Duplicates allowed

leetcode Insert Delete GetRandom O(1) - Duplicates allowed

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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();

题目地址:leetcode Insert Delete GetRandom O(1) - Duplicates allowed

题目大意: 要求实现一个数据结构(数允许重复),可以支持插入,删除,随机数生成。 他们的复杂度均要求O(1)

思路:其实和上一题  leetcode Insert Delete GetRandom O(1) 差不多,只不过这题允许重复,把字典里换成一个哈希表的set即可(注意,不可以是list)

比如如下的数据,list无法保证顺序!特别感谢@guanglightman 指出

1
2
["RandomizedCollection", "insert", "insert", "insert", "insert", "insert", "insert", "insert", "insert","remove", "remove", "remove", "remove", "remove", "remove"]
[[], [3], [4], [5], [6], [1], [2], [1], [2], [3], [4], [5], [6], [2], [2]]

 

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class RandomizedCollection {
private:
unordered_map<int, unordered_set<int>> index;
vector<int> output;
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) {
bool return_val = index.find(val) == index.end();
index[val].insert(output.size());
output.push_back(val);
return return_val;
}

/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if (index.find(val) == index.end()) return false;
int last = output.back(); output.pop_back();
index[last].erase(output.size());
if (last != val) {
int _id = *index[val].begin(); index[val].erase(_id);
index[last].insert(_id);
output[_id] = last;
}
if (index[val].empty())
index.erase(val);
return true;
}

/** Get a random element from the collection. */
int getRandom() {
return output[rand() % output.size()];
}
};

 

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import random

class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.index = collections.defaultdict(set)
self.output = []

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
"""
return_val = val not in self.index
self.index[val].add(len(self.output))
self.output.append(val)
return return_val

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.index: return False
last = self.output.pop()
self.index[last].remove(len(self.output))
if val != last:
index = self.index[val].pop()
self.index[last].add(index)
self.output[index] = last
if not self.index[val]:
del self.index[val]
return True

def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
return self.output[random.randint(0, len(self.output) - 1)]

 

本题是leetcode 381 Insert Delete GetRandom O(1) - Duplicates allowed 的题解

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~