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 being called that J are on the ' right ' of I.
For any interval I, your need to store the minimum interval J's index, which means that the interval J have the minimum star T 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 are always bigger than their start point.
- You may assume none of these intervals has the same start point.
Example 1:
Input: [[]]output: [ -1]explanation:there is only one interval in the collection, so it outputs-1.
Example 2:
Input: [[3,4], [2,3], []output]: [-1, 0, 1]explanation:there is no satisfied ' right ' interval for [3,4]. For [2,3], the interval [3,4] have minimum-' right ' start point; For [up to], 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].f or [2,3], the interval [3,4] has minimum-' right ' start point.
Solution: To sort these interval according to start from small to large, and then to each of the interval with its end to the queue in order to do two-point search,
Find a interval that meets the requirements. Code:
Public int[] findrightinterval (interval[] intervals) {interval[] sortedintervals=arrays.copyof (intervals,intervals.length); Arrays.sort (Sortedintervals, (O1, O2)O1.start-O2.start); int[] result =New int[Intervals.length]; for(inti = 0; i < intervals.length; i++) {Interval current=Intervals[i]; intInsertindex = Arrays.binarysearch (Sortedintervals, Current, (O1, O2)-O1.start-o2.end); if(Insertindex < 0) {Insertindex=-insertindex-1; } if(Insertindex = =intervals.length) {Result[i]=-1; }Else{Interval match=Sortedintervals[insertindex]; for(intj = 0; J < Intervals.length; J + +){ if(I! = J && Match.start = = Intervals[j].start && Match.end = =intervals[j].end) { //System.out.println (", Old index:" +j);Result[i] =J; } } } } returnresult; }
[leetcode]436 Find Right Interval