GFG上的一道数据结构的题:
http://geeksquiz.com/data-structure-n-elements-o1-operations/
设计一个数据结构插入删除和查找都是O(1),存储 0 - n-1
最初想法是hashtable类似,基于链表,但是查找不可能为O(1), 看了gfg上的讲解才豁然开朗。
Solution:
就是用一个数组实现,因为要存的数已知,0 到n-1,
数字 i 存在就把A[i] 设为true,mark
不存在就设为false
实现非常简单了
boolean A[];
public void initialize(int n){
A = new boolean[n];
Arrays.fill(A, false);
//or no need to initialize in java
}
//Insert an element
public void insert(int i){
A[i] = true;
}
//Delete an element
public void delete(int i){
A[i] = false;
}
public int deletelement(int i){
if(A[i] == true){
A[i] = false;
return 0;
}else{
return -1; // failure
}
}
//Find an element
public boolean find(int i){
return A[i];
}