-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path13-insert-delete-getrandom-o1.rs
57 lines (49 loc) · 1.47 KB
/
13-insert-delete-getrandom-o1.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
// https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
use std::collections::{HashMap};
struct RandomizedSet {
map: HashMap<i32, usize>,
list: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl RandomizedSet {
fn new() -> Self {
return Self {
map: HashMap::new(),
list: vec![],
};
}
fn insert(&mut self, val: i32) -> bool {
if self.map.contains_key(&val) { false } else {
self.list.push(val);
self.map.insert(val,self.list.len()-1);
true
}
}
fn remove(&mut self, val: i32) -> bool {
if !self.map.contains_key(&val) {
false
}else {
let &index = self.map.get(&val).unwrap();
let &last = self.list.last().unwrap();
self.list[index] = last;
self.list.pop();
self.map.insert(last, index);
self.map.remove(&val);
true
}
}
fn get_random(&self) -> i32 {
let rand_number = rand::random::<usize>() % self.list.len();
self.list[rand_number]
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* let obj = RandomizedSet::new();
* let ret_1: bool = obj.insert(val);
* let ret_2: bool = obj.remove(val);
* let ret_3: i32 = obj.get_random();
*/