简体   繁体   中英

Filter method time complexity in a TreeSet

val x = TreeSet<Int>(compareBy { it.toString() })
x.add(2);
x.add(4)
x.add(5)
x.add(15)
x.add(1)
x.add(34)
println(x)
print(x.filter { it in 5..19 })

I have some usecase similar to one metioned as sample code above. I have a bunch of data(size could be pretty huge) consider a timeseries, I need to filter out those items from the list which are between 2 dates? Is there a better solution than O(n) approach?

The problem here is that your TreeSet is sorted not in the same order as range, so we can't just find range boundaries in TreeSet and take all in between.

If TreeSet was sorted in natural order ( val x = TreeSet<Int>() ), you could just do:

val subset = x.subSet(5, true, 19, true)

This operation is almost free (O(1)), you just pay (O(log(N))) for iterating over this TreeSet (iterator construction will require two lookup-s for subset boundaries).

Afterwise, you may sort it in derisered way:

println(subset.toSortedSet(compareBy { it.toString() }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM