Skip to content

Instantly share code, notes, and snippets.

@mdrokz
Created May 30, 2023 15:09
Show Gist options
  • Save mdrokz/c83b910cb58f2ce166287da7d1314731 to your computer and use it in GitHub Desktop.
Save mdrokz/c83b910cb58f2ce166287da7d1314731 to your computer and use it in GitHub Desktop.
Leetcode problem 705 design a hashset implemented in rust
struct MyHashSet {
buckets: Vec<Vec<i32>>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyHashSet {
fn new() -> Self {
Self {
buckets: vec![vec![]; 1000],
}
}
fn hash(&self,k: i32) -> usize {
(k as usize) % 1000
}
pub fn add(&mut self, key: i32) {
let bucket_index = self.hash(key);
if !self.buckets[bucket_index].contains(&key) {
self.buckets[bucket_index].push(key);
}
}
pub fn remove(&mut self, key: i32) {
let bucket_index = self.hash(key);
if let Some(pos) = self.buckets[bucket_index].iter().position(|&x| x == key) {
self.buckets[bucket_index].remove(pos);
}
}
pub fn contains(&self, key: i32) -> bool {
let bucket_index = self.hash(key);
self.buckets[bucket_index].contains(&key)
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* let obj = MyHashSet::new();
* obj.add(key);
* obj.remove(key);
* let ret_3: bool = obj.contains(key);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment