-
Notifications
You must be signed in to change notification settings - Fork 2
/
design-hashmap.rs
82 lines (67 loc) · 1.8 KB
/
design-hashmap.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
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
/**
* Your MyHashMap object will be instantiated and called as such:
* let obj = MyHashMap::new();
* obj.put(key, value);
* let ret_2: i32 = obj.get(key);
* obj.remove(key);
*/
struct Node {
key: i32,
value: i32,
}
struct MyHashMap {
array: Vec<std::collections::LinkedList<Node>>,
}
impl MyHashMap {
fn new() -> Self {
Self {
array: (0..1001)
.map(|_| std::collections::LinkedList::new())
.collect(),
}
}
fn put(&mut self, key: i32, value: i32) {
let index = key as usize / 1000;
let mut iter = self.array[index].iter_mut();
while let Some(n) = iter.next() {
if n.key == key {
n.value = value;
return;
}
}
self.array[index].push_back(Node { key, value });
}
fn get(&self, key: i32) -> i32 {
let index = key as usize / 1000;
let mut iter = self.array[index].iter();
while let Some(n) = iter.next() {
if n.key == key {
return n.value;
}
}
-1
}
fn remove(&mut self, key: i32) {
let index = key as usize / 1000;
let mut iter = self.array[index].iter();
let mut x = None;
for (i, n) in iter.enumerate() {
if n.key == key {
x = Some(i);
break;
}
}
if let Some(x) = x {
let mut m = self.array[index].split_off(x);
m.pop_front();
self.array[index].append(&mut m);
}
}
}