- Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinsert-delete-getrandom-o1-duplicates-allowed.rs
102 lines (89 loc) · 2.92 KB
/
insert-delete-getrandom-o1-duplicates-allowed.rs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#![allow(dead_code, unused, unused_variables)]
use rand::Rng;
fnmain(){
letmut r = RandomizedCollection::new();
assert!(r.insert(1));
assert!(!r.insert(1));
assert!(r.insert(2));
assert!(r.remove(1));
println!("{}", r.get_random());
println!("{}", r.get_random());
println!("{}", r.get_random());
println!("{}", rand::thread_rng().gen_range(0..10));
println!("{}", rand::thread_rng().gen_range(0..10));
println!("{}", rand::thread_rng().gen_range(0..10));
println!("{}", rand::thread_rng().gen_range(0..10));
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* let obj = RandomizedCollection::new();
* let ret_1: bool = obj.insert(val);
* let ret_2: bool = obj.remove(val);
* let ret_3: i32 = obj.get_random();
*/
structRandomizedCollection{
data:Vec<i32>,
indexes: std::collections::HashMap<i32, std::collections::HashMap<usize,()>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
implRandomizedCollection{
/** Initialize your data structure here. */
fnnew() -> Self{
Self{
data:Vec::new(),
indexes: std::collections::HashMap::new(),
}
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
fninsert(&mutself,val:i32) -> bool{
let has = self.indexes.get(&val).is_some();
self.data.push(val);
let index = self.data.len() - 1;
self.indexes
.entry(val)
.and_modify(|i| {
i.insert(index,());
})
.or_insert_with(|| {
letmut h = std::collections::HashMap::new();
h.insert(index,());
h
});
!has
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
fnremove(&mutself,val:i32) -> bool{
ifself.indexes.get(&val).is_none(){
returnfalse;
}
let index = {
let i = *self.indexes.get(&val).unwrap().keys().next().unwrap();
self.indexes.get_mut(&val).unwrap().remove(&i);
i
};
let l = self.data.len() - 1;
let last = self.data[l];
self.data.swap(index, l);
if l != index {
self.indexes.entry(last).and_modify(|x| {
x.remove(&l);
x.insert(index,());
});
}
self.data.pop();
ifself.indexes.get(&val).unwrap().is_empty(){
self.indexes.remove(&val);
}
true
}
/** Get a random element from the collection. */
fnget_random(&self) -> i32{
use rand::Rng;
letmut rng = rand::thread_rng();
let index = rng.gen_range(0..self.data.len());
self.data[index]
}
}