diff options
Diffstat (limited to 'design-hashmap/src')
-rw-r--r-- | design-hashmap/src/main.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/design-hashmap/src/main.rs b/design-hashmap/src/main.rs new file mode 100644 index 0000000..f35bd69 --- /dev/null +++ b/design-hashmap/src/main.rs @@ -0,0 +1,43 @@ +fn main() { + println!("Hello, world!"); + let mut a = MyHashMap::new(); + a.put(1,1); + a.put(2,2); + a.get(1); + a.get(3); + a.put(2,1); + a.get(2); + a.remove(2); + a.get(2); +} + +struct MyHashMap { + map: Vec<(i32,i32)> +} + +impl MyHashMap { + + fn new() -> Self { + MyHashMap { + map: Vec::new() + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.map.iter_mut().find(|x| x.0 == key) { + Some(e) => e.1 = value, + None => self.map.push((key, value)) + }; + } + + fn get(&self, key: i32) -> i32 { + self.map.iter().find(|&x| x.0 == key).map(|x| x.1).unwrap_or(-1) + } + + fn remove(&mut self, key: i32) { + if let Some(e) = self.map.iter().position(|x| x.0 == key) { + self.map.swap_remove(e); + } + } +} + |