Design a Skiplist without using any built-in libraries.
A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.
For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).
Skiplist() Initializes the object of the skiplist.
bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.
void add(int num) Inserts the value num into the SkipList.
bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not exist in the Skiplist, do nothing and return false. If there exist multiple num values, removing any one of them is fine.
Note that duplicates may exist in the Skiplist, your code needs to handle this situation.
classNode:__slots__=['val','next']def__init__(self,val:int,level:int):self.val=valself.next=[None]*levelclassSkiplist:max_level=32p=0.25def__init__(self):self.head=Node(-1,self.max_level)self.level=0defsearch(self,target:int)->bool:curr=self.headforiinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,target)ifcurr.next[i]andcurr.next[i].val==target:returnTruereturnFalsedefadd(self,num:int)->None:curr=self.headlevel=self.random_level()node=Node(num,level)self.level=max(self.level,level)foriinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,num)ifi<level:node.next[i]=curr.next[i]curr.next[i]=nodedeferase(self,num:int)->bool:curr=self.headok=Falseforiinrange(self.level-1,-1,-1):curr=self.find_closest(curr,i,num)ifcurr.next[i]andcurr.next[i].val==num:curr.next[i]=curr.next[i].next[i]ok=Truewhileself.level>1andself.head.next[self.level-1]isNone:self.level-=1returnokdeffind_closest(self,curr:Node,level:int,target:int)->Node:whilecurr.next[level]andcurr.next[level].val<target:curr=curr.next[level]returncurrdefrandom_level(self)->int:level=1whilelevel<self.max_levelandrandom.random()<self.p:level+=1returnlevel# Your Skiplist object will be instantiated and called as such:# obj = Skiplist()# param_1 = obj.search(target)# obj.add(num)# param_3 = obj.erase(num)
classSkiplist{privatestaticfinalintMAX_LEVEL=32;privatestaticfinaldoubleP=0.25;privatestaticfinalRandomRANDOM=newRandom();privatefinalNodehead=newNode(-1,MAX_LEVEL);privateintlevel=0;publicSkiplist(){}publicbooleansearch(inttarget){Nodecurr=head;for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,target);if(curr.next[i]!=null&&curr.next[i].val==target){returntrue;}}returnfalse;}publicvoidadd(intnum){Nodecurr=head;intlv=randomLevel();Nodenode=newNode(num,lv);level=Math.max(level,lv);for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,num);if(i<lv){node.next[i]=curr.next[i];curr.next[i]=node;}}}publicbooleanerase(intnum){Nodecurr=head;booleanok=false;for(inti=level-1;i>=0;--i){curr=findClosest(curr,i,num);if(curr.next[i]!=null&&curr.next[i].val==num){curr.next[i]=curr.next[i].next[i];ok=true;}}while(level>1&&head.next[level-1]==null){--level;}returnok;}privateNodefindClosest(Nodecurr,intlevel,inttarget){while(curr.next[level]!=null&&curr.next[level].val<target){curr=curr.next[level];}returncurr;}privatestaticintrandomLevel(){intlevel=1;while(level<MAX_LEVEL&&RANDOM.nextDouble()<P){++level;}returnlevel;}staticclassNode{intval;Node[]next;Node(intval,intlevel){this.val=val;next=newNode[level];}}}/** * Your Skiplist object will be instantiated and called as such: * Skiplist obj = new Skiplist(); * boolean param_1 = obj.search(target); * obj.add(num); * boolean param_3 = obj.erase(num); */
structNode{intval;vector<Node*>next;Node(intv,intlevel):val(v),next(level,nullptr){}};classSkiplist{public:constintp=RAND_MAX/4;constintmaxLevel=32;Node*head;intlevel;Skiplist(){head=newNode(-1,maxLevel);level=0;}boolsearch(inttarget){Node*curr=head;for(inti=level-1;~i;--i){curr=findClosest(curr,i,target);if(curr->next[i]&&curr->next[i]->val==target)returntrue;}returnfalse;}voidadd(intnum){Node*curr=head;intlv=randomLevel();Node*node=newNode(num,lv);level=max(level,lv);for(inti=level-1;~i;--i){curr=findClosest(curr,i,num);if(i<lv){node->next[i]=curr->next[i];curr->next[i]=node;}}}boolerase(intnum){Node*curr=head;boolok=false;for(inti=level-1;~i;--i){curr=findClosest(curr,i,num);if(curr->next[i]&&curr->next[i]->val==num){curr->next[i]=curr->next[i]->next[i];ok=true;}}while(level>1&&!head->next[level-1])--level;returnok;}Node*findClosest(Node*curr,intlevel,inttarget){while(curr->next[level]&&curr->next[level]->val<target)curr=curr->next[level];returncurr;}intrandomLevel(){intlv=1;while(lv<maxLevel&&rand()<p)++lv;returnlv;}};/** * Your Skiplist object will be instantiated and called as such: * Skiplist* obj = new Skiplist(); * bool param_1 = obj->search(target); * obj->add(num); * bool param_3 = obj->erase(num); */
funcinit(){rand.Seed(time.Now().UnixNano())}const(maxLevel=16p=0.5)typenodestruct{valintnext[]*node}funcnewNode(val,levelint)*node{return&node{val:val,next:make([]*node,level),}}typeSkipliststruct{head*nodelevelint}funcConstructor()Skiplist{returnSkiplist{head:newNode(-1,maxLevel),level:1,}}func(this*Skiplist)Search(targetint)bool{p:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,target)ifp.next[i]!=nil&&p.next[i].val==target{returntrue}}returnfalse}func(this*Skiplist)Add(numint){level:=randomLevel()iflevel>this.level{this.level=level}node:=newNode(num,level)p:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,num)ifi<level{node.next[i]=p.next[i]p.next[i]=node}}}func(this*Skiplist)Erase(numint)bool{ok:=falsep:=this.headfori:=this.level-1;i>=0;i--{p=findClosest(p,i,num)ifp.next[i]!=nil&&p.next[i].val==num{p.next[i]=p.next[i].next[i]ok=true}}forthis.level>1&&this.head.next[this.level-1]==nil{this.level--}returnok}funcfindClosest(p*node,level,targetint)*node{forp.next[level]!=nil&&p.next[level].val<target{p=p.next[level]}returnp}funcrandomLevel()int{level:=1forlevel<maxLevel&&rand.Float64()<p{level++}returnlevel}/** * Your Skiplist object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Search(target); * obj.Add(num); * param_3 := obj.Erase(num); */