Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.
For any interval i, you need to store the minimum interval j's index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.
Note:
- You may assume the interval's end point is always bigger than its start point.
- You may assume none of these intervals have the same start point.
Example 1:
Input: [ [1,2] ] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1.
Example 2:
Input: [ [3,4], [2,3], [1,2] ] Output: [-1, 0, 1] Explanation: There is no satisfied "right" interval for [3,4]. For [2,3], the interval [3,4] has minimum-"right" start point; For [1,2], the interval [2,3] has minimum-"right" start point.
Example 3:
Input: [ [1,4], [2,3], [3,4] ] Output: [-1, 2, -1] Explanation: There is no satisfied "right" interval for [1,4] and [3,4].For [2,3], the interval [3,4] has minimum-"right" start point.
原题如上所示:
1.咋一看,肯定会有很多人想到用最笨的方法,也就是全部遍历直到找到那个大于等于它的end的最小start,但是这种情况显示超时。确实,时间复杂度为O(n^2),代码如下:
public class Solution { public int[] findRightInterval(Interval[] intervals) { int length=intervals.length; int[] ret=new int [length]; for(int i=0;i<length;i++){ int interval=Integer.MAX_VALUE; int flag=-1; for(int j=0;j<length;j++) if(intervals[j].start>=intervals[i].end&&interval>=intervals[j].start-intervals[i].end){ interval=intervals[j].start-intervals[i].end; flag=j; } ret[i]=flag; } return ret; } }
提交的结果是超时。
2.第二种思想就要考虑利用集合类了,时间复杂度为O(NlgN)回想到TreeMap中自带有两个函数higherEntry(key)和ceilingEntry(key);这两个函数的作用是:higherEntry(key)返回大于键的最小键,如果不存在则返回null
ceilingEntry(key)返回大于或等于键的最小键,如果不存在则返回null。所以完美的解决了这个问题,算法分为以下两步骤:
1)建立一个TreeMap,用来保存起始点和位置。
2)遍历intervals,调用treemap的两个函数,找到相应的键值对。
具体函数代码如下:
public class Solution { public int[] findRightInterval(Interval[] intervals) { int length=intervals.length; int []ret =new int[length];
//第一步骤,定义键值对 TreeMap<Integer,Integer> tMap=new TreeMap<Integer,Integer>(); for(int i=0;i<length;i++){ tMap.put(intervals[i].start, i); }
//第二步骤,调用函数来找到目标键值对 for(int i=0;i<length;i++){ Map.Entry<Integer, Integer> entry=tMap.ceilingEntry(intervals[i].end);
//Map.Entry<Integer, Integer> entry=tMap.higherEntry(intervals[i].end-1); if(entry!=null) ret[i]=entry.getValue(); else ret[i]=-1; } return ret; } }
考虑到最近遇到了不少TreeMap,HashMap以及相关的HashTable的问题,下一篇博客决定来比较下这几种集合类的区别。