Last active
December 24, 2015 23:39
-
-
Save Yangff/6881708 to your computer and use it in GitHub Desktop.
A javascript multiset with O(logN) insert , delete and Query.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Set | |
constructor :(array=[])-> | |
@ary = array | |
@pos = {} | |
for value,key in @ary | |
if @pos.hasOwnProperty value | |
@pos[value].push key | |
else | |
@pos[value] = [key] | |
insert :(element)-> | |
@ary.push element | |
if @pos.hasOwnProperty element | |
@pos[element].push @ary.length-1 | |
else | |
@pos[element] = [@ary.length-1] | |
remove :(element)-> | |
#console.log "remove " + element | |
return unless @pos.hasOwnProperty element | |
effection = {} | |
for p in @pos[element] | |
if (p == @ary.length-1) | |
@ary.pop() | |
else | |
@ary[p] = @ary[@ary.length-1] | |
effection[@ary[p]] = {} unless effection.hasOwnProperty @ary[p] | |
effection[@ary[p]][@ary.length-1] = p | |
@ary.pop() | |
delete @pos[element] | |
#console.log(effection) | |
for key,value of effection | |
for k,v of @pos[key] | |
# console.log("set " + @pos[key][k] + " to " +value[v] ) | |
@pos[key][k] = value[v] if value[v] != null | |
0 | |
size : -> | |
@ary.length | |
getValue : (k)-> | |
@ary[k] | |
getKey : (v)-> | |
@pos[v] | |
exports.Set = Set |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment