-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0380-insert-delete-getrandom-o1.rs
More file actions
40 lines (37 loc) · 990 Bytes
/
0380-insert-delete-getrandom-o1.rs
File metadata and controls
40 lines (37 loc) · 990 Bytes
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
use rand::seq::SliceRandom;
use std::collections::HashMap;
pub struct RandomizedSet {
mp: HashMap<i32, i32>,
arr: Vec<i32>,
}
impl RandomizedSet {
fn new() -> Self {
RandomizedSet {
mp: HashMap::new(),
arr: Vec::new(),
}
}
fn insert(&mut self, val: i32) -> bool {
let res = !self.mp.contains_key(&val);
if res {
self.mp.insert(val, self.arr.len() as i32);
self.arr.push(val);
}
res
}
fn remove(&mut self, val: i32) -> bool {
let res = self.mp.contains_key(&val);
if res {
let idx = *self.mp.get(&val).unwrap();
self.mp
.entry(*self.arr.last().unwrap())
.and_modify(|v| *v = idx);
self.arr.swap_remove(idx as usize);
self.mp.remove(&val);
}
res
}
fn get_random(&self) -> i32 {
*self.arr.choose(&mut rand::thread_rng()).unwrap()
}
}