How to retrieve elements from sorted TreeSet using Binary Search?

谁都会走 提交于 2019-12-01 10:38:26

TreeSet is backed by a NavigableMap, a TreeMap specifically. Calling contains() on a TreeSet delegates to TreeMap.containsKey(), which is a binary search implementation.

You can check if an object is contained in the set by using TreeSet.contains(), but you have to have the object first. If you want to be able to look up and retrieve an object, then a Map implementation will be better.

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<List<Integer>> 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<Integer>" 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));

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!