How to retrieve elements from sorted TreeSet using Binary Search?

前端 未结 3 830
春和景丽
春和景丽 2021-01-14 10:20

I am trying to merge multiple sorted lists into one TreeSet.. And then I am thinking to apply Binary Search algorithm on that TreeSet to retrieve the element in O(log n) tim

3条回答
  •  -上瘾入骨i
    2021-01-14 10:58

    TreeSet, by it's nature is a sorted set and uses a red-tree-black-tree via TreeMap as it's backing

    Basically: TreeSet.add(E) -> TreeMap.put(E,NULL);

    As it is already a binary, sorted tree structure any 'get' or 'contains' will result in an O(log n) operation.

    Your code and your question though don't line up.

    You're flattening a List> and just putting them all in to get all unique elements (or, at least, that's what this code will do).

    But then your following method says "given this integer, give me a List" which isn't achievable in the above code

    So, let me answer your questions in order:

    1. Sure/Yes Y
    2. No. You misunderstand Sets (you can't extract by design) If you can do Set.contains(e) then you HAVE the element and need not extract anything

    If you need to do something like a "Set extraction" then use a TreeMap or turn your set back into a list and do myList.get(Collections.binarySearch(myElement));

提交回复
热议问题