网易笔试题,实现一个hashtable,使得他的set,get,setAll时间复杂度都是O()

public class HashTable {
public class Entry {
String value;
int currentSet;
}

private Entry[] list = new Entry[10];
int globalSet;
String globalValue;

public void set(int key, String value) {
Entry temp = list[key];
if (temp == null) {
temp = new Entry();
list[key] = temp;
}
temp.value = value;
temp.currentSet = globalSet;
}

public void setAll(String value) {
globalSet++;
globalValue = value;
}

public String get(int key) {
Entry temp = list[key];
if (temp == null) {
return null;
}
if (temp.currentSet < globalSet) {
return globalValue;
}
return temp.value;
}
}

更具有扩展性的可以用hashcode作为index

hash ^= (hash >>> 20) ^ (hash >>> 12);

hash ^= (hash >>> 7) ^ (hash >>> 4);

index = hash&(table.length-1)


你可能感兴趣的:(算法研究)