Skip to content

Commit c4ce371

Browse files
author
lightmen
committed
add insert-delete-getrandom-o1-duplicates-allowed.py
1 parent 7a42554 commit c4ce371

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class RandomizedCollection(object):
2+
3+
def __init__(self):
4+
"""
5+
Initialize your data structure here.
6+
"""
7+
self.d = collections.defaultdict(set)
8+
self.l = []
9+
10+
def insert(self, val):
11+
"""
12+
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
13+
:type val: int
14+
:rtype: bool
15+
"""
16+
bool_ret = val not in self.l
17+
self.d[val].add(len(self.l))
18+
self.l.append(val)
19+
return bool_ret
20+
21+
def remove(self, val):
22+
"""
23+
Removes a value from the collection. Returns true if the collection contained the specified element.
24+
:type val: int
25+
:rtype: bool
26+
"""
27+
if val not in self.l:
28+
return False
29+
last_val = self.l.pop()
30+
self.d[last_val].remove(len(self.l))
31+
if val != last_val:
32+
index = self.d[val].pop()
33+
self.l[index] = last_val
34+
self.d[last_val].add(index)
35+
36+
if not self.d[val]:
37+
del self.d[val]
38+
return True
39+
40+
def getRandom(self):
41+
"""
42+
Get a random element from the collection.
43+
:rtype: int
44+
"""
45+
return self.l[random.randint(0, len(self.l) - 1)]
46+
47+
# Your RandomizedCollection object will be instantiated and called as such:
48+
# obj = RandomizedCollection()
49+
# param_1 = obj.insert(val)
50+
# param_2 = obj.remove(val)
51+
# param_3 = obj.getRandom()
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution(object):
2+
def frequencySort(self, s):
3+
"""
4+
:type s: str
5+
:rtype: str
6+
"""
7+
return ''.join(c * t for c, t in collections.Counter(s).most_common())

0 commit comments

Comments
 (0)