Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structure, and the values are their positions in the array.
- insert(value): append the value to array and let i be it’s index in A. Set H[value]=i.
- remove(value): We are going to replace the cell that contains value in A with the last element in A. let d be the last element in the array A at index m. let i be H[value], the index in the array of the value to be removed. Set A[i]=d, H[d]=i, decrease the size of the array by one, and remove value from H.
- contains(value): return H.contains(value)
- getRandomElement(): let r=random(current size of A). return A[r].
//ArrayList + HashMap
//remove的时候把最后一个元素拿过来补上
interface List<T> {
public void add(T o); // add to the last
public T get(int index); // get the index object
public int size(); // return the size
public boolean remove(T o); // remove the first o and return true; if not exist,
// return false.
}
public class ListImpl implements List<T> {
private class ListNode {
T val;
ListNode prev, next;
ListNode(T val) {
this.val = val;
}
}
Map<T, LinkedList<ListNode>> hm;
ListNode dummyHead, dummyTail;
public ListImpl() {
hm = new HashMap<T, LinkedList<ListNode>>();
dummyHead = new ListNode(null);
dummyTail = new ListNode(null);
}
public void add(T o) {
}
}