Implement the hash table using array / binary search tree
今天在复习Arrays and String 时看到一个很有趣的问题。希望跟大家分享一下。
Implement the hash table using array / binary search tree
1. Using Array/LinkedList:
1) key需要通过hash 来得到array中的index
2) array的每一位都是放着一个list
3) 需要自己定义一个class,list 由这个class 类型组成
4) 要考虑到万一hashvalue 范围很大,需要把table的size压缩: %TABLE_SIZE;
class LinkedHashEntry { String key; int value; LinkedHashEntry next; LinkedHashEntry(String key, int value) { this.key = key; this.value = value; this.next = null; } } public class HashTable { private int TABLE_SIZE; private int size; private LinkedHashEntry[] table; // Constructor HashTable(int ts) { size = 0; TABLE_SIZE = ts; table = new LinkedHashEntry[TABLE_SIZE]; for(int i = 0; i < TABLE_SIZE; i ++) { table[i] = null; } } // hash function private int myhash(String key) { int hashValue = key.hashCode(); hashValue %= TABLE_SIZE; if(hashValue < 0) { hashValue += TABLE_SIZE; } return hashValue; } // hash put function public void put(String key, int value) { int hash = (myhash(key) % TABLE_SIZE); if(table[hash] == null) { table[hash] = new LinkedHashEntry(key, value); } else { LinkedHashEntry entry = table[hash]; while(entry.next != null && !entry.key.equals(key)) { entry = entry.next; } if(entry.key.equals(key)) { entry.value = value; // if we have already put this pair of key value } else { entry.next = new LinkedHashEntry(key, value); } } size ++; } public int getValue(String key) { int hash = (myhash(key) % TABLE_SIZE); if(table[hash] == null) { return -1; } else { LinkedHashEntry entry = table[hash]; while(entry.next != null && !entry.key.equals(key)) { entry = entry.next; } if(entry.key.equals(key)) { return entry.value; } else { return -1; } } } public void remove(String key, int value) { int hash = (myhash(key)% TABLE_SIZE); if(table[hash] == null) { return; } else { LinkedHashEntry preEntry = null; LinkedHashEntry entry = table[hash]; while(entry.next != null && !entry.key.equals(key)) { preEntry = entry; entry = entry.next; } if(entry.key.equals(key)) { if(preEntry == null) { table[hash] = entry.next; } else { preEntry.next = entry.next; } size --; } } } public int size() { return size; } }
2. Using BST
在craking coding interview 这本书上看到这个问题,但是并没有想清楚这个问题的解决方法,希望有大神可以解答。谢谢!