Data structure:insert,remove,contains,get random element,all at O(1)

2013 ワード

From:
http://stackoverflow.com/questions/5682218/data-structure-insert-remove-contains-get-random-element-all-at-o1
Design a data structure that offrs the follwing operations in(1)time:
insert remove contains get random element Solution:
Consder a data structure computed of a hashtable H and an array A.The hashtable keys are the elemens in the data structure,and the values are their positions in the array.
insert(value):apped the value to array and let i be it's index in A.Set H[value]=i.remove(value):We ararararare going to replace the cel that contains value in A with the last elemenn in A.let d d be the last element in the ararray A aa a a aa index m.let i be H[value],the index the index the ininininininininthe the the the the the the the arararaaaaaaaaaaaaaaaaaaaaathe the the the the the aaaaaaaaaaaaaathe the the the the the the the the lue from H.contains(value):return H.co ntains(value)get RandomElement():let r=randm(current size of A).return A[r].since the array needs to aut-inncrease in size,it's going to be amortize O(1)to add an element,but I gess that's OK.
public class ConstantRandomGet<E> {

	private Map<E, Integer> map = new HashMap<>();
	private List<E> list = new ArrayList<>();
	private Random random = new Random();
	
	public void insert(E e) {
		map.put(e, list.size());
		list.add(e);
	}
	
	public boolean remove(E e) {
		if(!map.containsKey(e)) return false;
		int i = map.get(e);
		int last = list.size()-1;
		E lastE = list.remove(last);
		map.put(lastE, i);
		list.set(i, lastE);
		return true;
	}
	
	public boolean contains(E e) {
		return map.containsKey(e);
	}
	
	public E getRandomElement() {
		int size = list.size();
		if(size == 0) return null;
		int index = random.nextInt(size);
		return list.get(index);
	}
}