How to return the k-th element in TreeSet in Java?

后端 未结 8 1998
-上瘾入骨i
-上瘾入骨i 2020-12-30 01:07

Maybe I am not using the right data structure. I need to use a set, but also want to efficiently return the k-th smallest element. Can TreeSet in Java do this?

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 01:48

    Could you use a ConcurrentSkipListSet and use the toArray() method? ConcurrentSkipListSet is sorted by the natural order of elements. The only thing I am not sure about is if the toArray() is O(n) or since it's backed by a List (backed by an array, like ArrayList) it's O(1).

    If toArray() is O(1) the you should be able to be a skipList.toArray()[k] to get the k-th smallest element.

提交回复
热议问题