705. Design HashSet Easy
1/**
2 * [705] Design HashSet
3 *
4 * Design a HashSet without using any built-in hash table libraries.
5 * Implement MyHashSet class:
6 *
7 * void add(key) Inserts the value key into the HashSet.
8 * bool contains(key) Returns whether the value key exists in the HashSet or not.
9 * void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
10 *
11 *
12 * Example 1:
13 *
14 * Input
15 * ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
16 * [[], [1], [2], [1], [3], [2], [2], [2], [2]]
17 * Output
18 * [null, null, null, true, false, null, true, null, false]
19 * Explanation
20 * MyHashSet myHashSet = new MyHashSet();
21 * myHashSet.add(1); // set = [1]
22 * myHashSet.add(2); // set = [1, 2]
23 * myHashSet.contains(1); // return True
24 * myHashSet.contains(3); // return False, (not found)
25 * myHashSet.add(2); // set = [1, 2]
26 * myHashSet.contains(2); // return True
27 * myHashSet.remove(2); // set = [1]
28 * myHashSet.contains(2); // return False, (already removed)
29 *
30 * Constraints:
31 *
32 * 0 <= key <= 10^6
33 * At most 10^4 calls will be made to add, remove, and contains.
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/design-hashset/
39// discuss: https://leetcode.com/problems/design-hashset/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43struct MyHashSet {
44 data: Vec<bool>
45}
46
47
48/**
49 * `&self` means the method takes an immutable reference.
50 * If you need a mutable reference, change it to `&mut self` instead.
51 */
52impl MyHashSet {
53
54 fn new() -> Self {
55 MyHashSet { data: vec![false; 1000001] }
56 }
57
58 fn add(&mut self, key: i32) {
59 self.data[key as usize] = true;
60 }
61
62 fn remove(&mut self, key: i32) {
63 self.data[key as usize] = false;
64 }
65
66 fn contains(&self, key: i32) -> bool {
67 self.data[key as usize]
68 }
69}
70
71/**
72 * Your MyHashSet object will be instantiated and called as such:
73 * let obj = MyHashSet::new();
74 * obj.add(key);
75 * obj.remove(key);
76 * let ret_3: bool = obj.contains(key);
77 */
78
79// submission codes end
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn test_705() {
87 let mut set = MyHashSet::new();
88 set.add(12);
89 assert!(set.contains(12))
90 }
91}
92
Back
© 2025 bowen.ge All Rights Reserved.