TreeMap is a Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys.
The time complexity for containsKey, get, put and removeoperations are O(logn).
Time complexity O(nlogn).
public class Solution {
public int[] findRightInterval(Interval[] intervals) {
int[] ret = new int[intervals.length];
// the key is the start point and value is the index for each interval
TreeMap<Integer, Integer> tm = new TreeMap<>();
// put all intervals into the map
for (int i=0; i<intervals.length; i++)
tm.put(intervals[i].start, i);
// for every start point in the map, find the cieling index of its end point
// TreeMap is binary search tree, the time complexity for finding the cieling is O(logn)
for (int j=0; j<intervals.length; j++) {
Map.Entry<Integer, Integer> entry = tm.ceilingEntry(intervals[j].end);
// there is no start point for a interval's end point
if (entry == null)
ret[j] = -1;
else
ret[j] = entry.getValue();
}
return ret;
}
}