Skip to content

Commit 913a3ac

Browse files
committed
create 0706 in rust
1 parent 191c85a commit 913a3ac

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: rust/0706-design-hashmap.rs

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
struct MyHashMap {
2+
buckets: Vec<Vec<(i32,i32)>>,
3+
}
4+
5+
// Prime number of buckets to reduce collisions
6+
const N_BUCKETS: usize = 1031;
7+
8+
impl MyHashMap {
9+
10+
fn new() -> Self {
11+
Self{ buckets: vec![vec![]; N_BUCKETS] }
12+
}
13+
14+
fn hash(key: i32) -> usize {
15+
key as usize % N_BUCKETS
16+
}
17+
18+
fn find_entry(&mut self, key: i32) -> (&mut Vec<(i32, i32)>, Result<usize, usize>) {
19+
let bucket = &mut self.buckets[Self::hash(key)];
20+
let result = bucket.binary_search_by(|(k, v)| k.cmp(&key));
21+
(bucket, result)
22+
}
23+
24+
fn put(&mut self, key: i32, value: i32) {
25+
match self.find_entry(key) {
26+
(bucket, Ok(index)) => bucket[index] = (key, value),
27+
(bucket, Err(index)) => bucket.insert(index, (key, value)),
28+
}
29+
}
30+
31+
fn get(&self, key: i32) -> i32 {
32+
let bucket = &self.buckets[Self::hash(key)];
33+
match bucket.binary_search_by(|(k, v)| k.cmp(&key)) {
34+
Ok(index) => bucket[index].1,
35+
Err(index) => -1,
36+
}
37+
}
38+
39+
fn remove(&mut self, key: i32) {
40+
match self.find_entry(key) {
41+
(bucket, Ok(index)) => { bucket.remove(index); },
42+
_ => (),
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)