LeetCode 705. Design HashSet

Description:
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.

Solution:
思路和hashmap实现思路一样,事实上,hashset底层就是基于hashmap的。

class MyHashSet {
    
    ListNode[] nodes = new ListNode[1000001];
    
    private class ListNode{
        
        int val;
        ListNode next; 
        ListNode(int val) {
            this.val = val;
        }
        
    }
    
    private int getIndex(int val){
        return Integer.hashCode(val) % 1000000;
    }
    
    //return the node before val, or return the final node
    private ListNode getElem(int val){
        int index = getIndex(val);
        //if null, then create the root(but not use it)
        if(nodes[index] == null){
            nodes[index] = new ListNode(-1);
            return nodes[index];
        }

        ListNode previous = nodes[index];

        while(previous.next != null && previous.next.val != val){
            previous = previous.next;
        }

        return previous;
        
    }

    /** Initialize your data structure here. */
    public MyHashSet() {
        
    }
    
    public void add(int key) {
        ListNode pre = getElem(getIndex(key));
        if(pre.next == null) {
            pre.next = new ListNode(key);
        } else {
            pre.next.val = key;
        }
    }
    
    public void remove(int key) {
        ListNode pre = getElem(getIndex(key));
        if(pre.next == null) {
            
        } else {
            pre.next = pre.next.next;
        }
    }
    
    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        ListNode pre = getElem(getIndex(key));
        if(pre.next == null) {
            return false;
        } else {
            return true;
        }
        
    }
}

/**
 * Your MyHashSet object will be instantiated and called as such:
 * MyHashSet obj = new MyHashSet();
 * obj.add(key);
 * obj.remove(key);
 * boolean param_3 = obj.contains(key);
 */

猜你喜欢

转载自blog.csdn.net/weixin_40037938/article/details/106155022