Design HashSet

Design a HashSet without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • add(value): Insert a value into the HashSet. 
  • contains(value) : Return whether the value exists in the HashSet or not.
  • remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.


Example:

MyHashSet hashSet = new MyHashSet();
hashSet.add(1);         
hashSet.add(2);         
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);          
hashSet.contains(2);    // returns true
hashSet.remove(2);          
hashSet.contains(2);    // returns false (already removed)

 1 class MyHashSet {
 2     final ListNode[] nodes = new ListNode[10000];
 3     /** Initialize your data structure here. */
 4     public MyHashSet() {
 5         
 6     }
 7     
 8     public void add(int key) {
 9         int i = idx(key);
10         ListNode first = nodes[i];
11         if (first == null) {
12             nodes[i] = new ListNode(key);
13         } else if (!exists(first, key)) {
14             ListNode newNode = new ListNode(key);
15             newNode.next = nodes[i];
16             nodes[i] = newNode;
17         }
18     }
19     
20     public void remove(int key) {
21         int i = idx(key);
22         if (nodes[i] == null) {
23             return;
24         }
25         ListNode current = nodes[i];
26         ListNode previous = null;
27         while (current != null) {
28             if (current.key == key) {
29                 if (previous != null) {
30                     previous.next = current.next;
31                 } else {
32                     nodes[i] = current.next;
33                 }
34                 break;
35             } else {
36                 previous = current;
37                 current = current.next;
38             }
39         }
40     }
41     
42     /** Returns true if this set contains the specified element */
43     public boolean contains(int key) {
44         int i = idx(key);
45         ListNode first = nodes[i];
46         if (first == null) {
47             return false; 
48         }
49         return exists(first, key);
50     }
51     
52     int idx(int key) {
53         return key % nodes.length;
54     }
55     
56     private boolean exists(ListNode node, int key) {
57         ListNode current = node;
58         while (current != null) {
59             if (current.key == key) {
60                 return true;
61             }
62             current = current.next;
63         }
64         return false;
65     }
66 }
67 
68 
69 class ListNode {
70     int key;
71     ListNode next;
72 
73     ListNode(int key) {
74         this.key = key;
75     }
76 }

猜你喜欢

转载自www.cnblogs.com/beiyeqingteng/p/11334086.html