classMyHashSet{ privatestaticfinalint base = 857; private LinkedList[] data;
/** * Initialize your data structure here. */ publicMyHashSet(){ data = new LinkedList[base]; for (int i = 0; i < base; i++) { data[i] = new LinkedList<Integer>(); } }
privatestaticinthash(int k){ return k % base; }
publicvoidadd(int key){ int pos = hash(key); Iterator<Integer> it = data[pos].iterator(); while (it.hasNext()) { Integer element = it.next(); if (element == key) { return; } } data[pos].offerLast(key); }
publicvoidremove(int key){ int pos = hash(key); Iterator<Integer> it = data[pos].iterator(); while (it.hasNext()) { Integer element = it.next(); if (element == key) { data[pos].remove(element); return; } } }
/** * Returns true if this set contains the specified element */ publicbooleancontains(int key){ int pos = hash(key); Iterator<Integer> it = data[pos].iterator(); while (it.hasNext()) { Integer element = it.next(); if (element == key) { returntrue; } } returnfalse; } }
privatestaticfinalint base = 857; private LinkedList[] data;
/** * Initialize your data structure here. */ publicMyHashMap(){ data = new LinkedList[base]; for (int i = 0; i < base; i++) { data[i] = new LinkedList<Pair>(); } }
privatestaticinthash(int k){ return k % base; }
/** * value will always be non-negative. */ publicvoidput(int key, int value){ int pos = hash(key); Iterator<Pair> it = data[pos].iterator(); while (it.hasNext()) { Pair element = it.next(); if (element.key == key) { element.setValue(value); return; } } data[pos].offerLast(new Pair(key, value)); }
/** * Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ publicintget(int key){ int pos = hash(key); Iterator<Pair> it = data[pos].iterator(); while (it.hasNext()) { Pair element = it.next(); if (element.key == key) { return element.value; } } return -1; }
/** * Removes the mapping of the specified value key if this map contains a mapping for the key */ publicvoidremove(int key){ int pos = hash(key); Iterator<Pair> it = data[pos].iterator(); while (it.hasNext()) { Pair element = it.next(); if (element.key == key) { data[pos].remove(element); return; } } } }