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) time complexity..
Below is my code in which I am passing List of Lists in in one of my method and combining them into TreeSet
to avoid duplicacy... All the lists inside inputs
are sorted -
private TreeSet<Integer> tree = new TreeSet<Integer>();
public void mergeMultipleLists(final List<List<Integer>> inputs) {
tree = new TreeSet<Integer>();
for (List<Integer> input : inputs) {
for(Integer ii : input) {
tree.add(ii);
}
}
}
public List<Integer> getItem(final Integer x) {
// extract elements from TreeSet in O(log n)
}
- First of all, is this right way to merge multiple sorted lists into TreeSet? Is there any direct way to merge multiple sorted lists in TreeSet efficiently?
- Secondly, how would I extract an element from that TreeSet in O(log n) time complexity? I would like to find an element
x
in thatTreeSet
, if it is there, then return it, if it is not there then return the next largest value from theTreeSet
.
Or may be I am better off to another data structure as compared to which I am using currently?
UPDATED CODE:-
private TreeSet tree = new TreeSet();
public SearchItem(final List<List<Integer>> inputs) {
tree = new TreeSet<Integer>();
for (List<Integer> input : inputs) {
tree.addAll(input);
}
}
public Integer getItem(final Integer x) {
if(tree.contains(x)) {
return x;
} else {
// now how do I extract next largest
// element from it if x is not present
}
}
TreeSet.addAll()
instead of adding each element individually. It'll save a few LOC but I don't know if it's any more perfomant. – DeemphasizeaddAll
.. I totally forgot that.. And now regarding my second question.. Any thoughts? – Latchetx
th largest element? Do you want to test ifx
is in theTreeSet
? Do you want to get the element that is equal tox
(in which case...you'd just returnx
?) – Incorporatex
in thatTreeSet
, if it is there, then return it, if it is not there then return the next largest value from theTreeSet
. – Latchet