【发布时间】:2014-03-26 18:18:33
【问题描述】:
只是寻找一些帮助/了解这个问题的问题..也许有人甚至可以为我指出正确的方向以最终解决它。
我目前有一个使用标准哈希函数的完整的独立链式哈希表算法:
(key.hashCode() & 0x7fffffff) % M
不管怎样,问题......
使用单独的链接将键 E A S Y Q U T I O N 按该顺序插入到最初为空的 M = 5 列表表中。使用哈希函数11 K % M将字母表中的第K个字母转化为表索引。
我绝不是散列专家,但在研究这个主题几周后,这个问题在我看来仍然是完全胡言乱语。
编辑 如果有帮助,这里是哈希表代码:
public class SeparateChainingHashST<Key, Value> {
private static final int INIT_CAPACITY = 4;
private int N; // number of key-value pairs
private int M; // hash table size
private SequentialSearchST<Key, Value>[] st; // array of linked-list symbol tables
// create separate chaining hash table
public SeparateChainingHashST() {
this(INIT_CAPACITY);
}
// create separate chaining hash table with M lists
public SeparateChainingHashST(int M) {
this.M = M;
st = (SequentialSearchST<Key, Value>[]) new SequentialSearchST[M];
for (int i = 0; i < M; i++)
st[i] = new SequentialSearchST<Key, Value>();
}
// resize the hash table to have the given number of chains b rehashing all of the keys
private void resize(int chains) {
SeparateChainingHashST<Key, Value> temp = new SeparateChainingHashST<Key, Value>(chains);
for (int i = 0; i < M; i++) {
for (Key key : st[i].keys()) {
temp.put(key, st[i].get(key));
}
}
this.M = temp.M;
this.N = temp.N;
this.st = temp.st;
}
// hash value between 0 and M-1
private int hash(Key key) {
return (key.hashCode() & 0x7fffffff) % M;
}
// return number of key-value pairs in symbol table
public int size() {
return N;
}
// is the symbol table empty?
public boolean isEmpty() {
return size() == 0;
}
// is the key in the symbol table?
public boolean contains(Key key) {
return get(key) != null;
}
// return value associated with key, null if no such key
public Value get(Key key) {
int i = hash(key);
return st[i].get(key);
}
// insert key-value pair into the table
public void put(Key key, Value val) {
if (val == null) { delete(key); return; }
// double table size if average length of list >= 10
if (N >= 10*M) resize(2*M);
int i = hash(key);
if (!st[i].contains(key)) N++;
st[i].put(key, val);
}
// delete key (and associated value) if key is in the table
public void delete(Key key) {
int i = hash(key);
if (st[i].contains(key)) N--;
st[i].delete(key);
// halve table size if average length of list <= 2
if (M > INIT_CAPACITY && N <= 2*M) resize(M/2);
}
// return keys in symbol table as an Iterable
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (int i = 0; i < M; i++) {
for (Key key : st[i].keys())
queue.enqueue(key);
}
return queue;
}
public static void main(String[] args) {
SeparateChainingHashST<String, Integer> st = new SeparateChainingHashST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
// print keys
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
【问题讨论】:
-
这不是一个真正的问题,而是一个指令。你的问题是什么,你想要什么样的答案?
-
@hatchet 这是一个指令,我认为遵循该指令是“问题”,成功地这样做是“答案”。我只是不确定如何遵循它,以及它要求我做什么
标签: java hash chaining sequential