Reputation: 149
Good day.
I use TreeSet
, for example TreeSet<Integer> t
.
And I want to print all numbers from set t between x and y.
void print(Integer x,Integer y, TreeSet<Integer> t){
...
}
How to do it?
Of Course I can get t.iterator()
, and iterator all numbers from set and check is it greats x and less y.
Time complexity is y steps.
but if y-x is small. It will be better to get t.higher() and after that iterate the elements in set until it less than y.
This solution can be implemented in C++.
And it's time complexity is log (t.size())+(y-x)
.
How to do in in Java?
Upvotes: 0
Views: 235
Reputation: 6242
You can use the SortedSet
interface (which TreeSet
implements). For example:
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i = 1; i <= 5; ++i) {
set.add(i);
}
int from = 2;
int to = 4;
for (int x : set.subSet(from, to+1)) { // Note that the higher bound is exclusive.
System.out.println(x);
}
Output:
2
3
4
Upvotes: 1