leetcode_rust/
design_hashset.rs

1#![allow(dead_code)]
2#![allow(unused_variables)]
3
4use std::collections::LinkedList;
5use std::iter;
6
7// use chain method
8pub struct MyHashSet {
9    bucket: Vec<LinkedList<i32>>,
10    len: i32,
11}
12
13impl MyHashSet {
14    /** Initialize your data structure here. */
15    pub fn new() -> Self {
16        let len: i32 = 2047;
17        let bucket = iter::repeat(LinkedList::new())
18            .take(len as usize)
19            .collect::<Vec<LinkedList<i32>>>();
20        Self { bucket, len }
21    }
22
23    pub fn add(&mut self, key: i32) {
24        if self.contains(key) {
25            return;
26        } else {
27            let index = self._hash(key);
28            let list = &mut self.bucket[index];
29            list.push_front(key);
30        }
31    }
32
33    pub fn remove(&mut self, key: i32) {
34        match self._find(key) {
35            None => {}
36            // zero never be used
37            Some(val) => *val = 0,
38        }
39    }
40
41    /** Returns true if this set contains the specified element */
42    #[inline]
43    pub fn contains(&mut self, key: i32) -> bool {
44        match self._find(key) {
45            Some(_) => true,
46            None => false,
47        }
48    }
49
50    #[inline]
51    fn _find(&mut self, key: i32) -> Option<&mut i32> {
52        let index = self._hash(key);
53        let list = &mut self.bucket[index];
54        for val in list.iter_mut() {
55            if *val == key {
56                return Some(val);
57            }
58        }
59
60        None
61    }
62
63    #[inline]
64    fn _hash(&self, key: i32) -> usize {
65        key as usize % self.len as usize
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn test1() {
75        let mut obj = MyHashSet::new();
76        let key = 1;
77        obj.add(key);
78        obj.remove(key);
79        let ret: bool = obj.contains(key);
80        assert_eq!(ret, false);
81    }
82}