|
| 1 | +# Time: O(nlogn) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +# Given a set of intervals, for each of the interval i, |
| 5 | +# check if there exists an interval j whose start point is bigger than or |
| 6 | +# equal to the end point of the interval i, which can be called that j is on the "right" of i. |
| 7 | +# |
| 8 | +# For any interval i, you need to store the minimum interval j's index, |
| 9 | +# which means that the interval j has the minimum start point to |
| 10 | +# build the "right" relationship for interval i. If the interval j doesn't exist, |
| 11 | +# store -1 for the interval i. Finally, you need output the stored value of each interval as an array. |
| 12 | +# |
| 13 | +# Note: |
| 14 | +# You may assume the interval's end point is always bigger than its start point. |
| 15 | +# You may assume none of these intervals have the same start point. |
| 16 | +# Example 1: |
| 17 | +# Input: [ [1,2] ] |
| 18 | +# |
| 19 | +# Output: [-1] |
| 20 | +# |
| 21 | +# Explanation: There is only one interval in the collection, so it outputs -1. |
| 22 | +# Example 2: |
| 23 | +# Input: [ [3,4], [2,3], [1,2] ] |
| 24 | +# |
| 25 | +# Output: [-1, 0, 1] |
| 26 | +# |
| 27 | +# Explanation: There is no satisfied "right" interval for [3,4]. |
| 28 | +# For [2,3], the interval [3,4] has minimum-"right" start point; |
| 29 | +# For [1,2], the interval [2,3] has minimum-"right" start point. |
| 30 | +# Example 3: |
| 31 | +# Input: [ [1,4], [2,3], [3,4] ] |
| 32 | +# |
| 33 | +# Output: [-1, 2, -1] |
| 34 | +# |
| 35 | +# Explanation: There is no satisfied "right" interval for [1,4] and [3,4]. |
| 36 | +# For [2,3], the interval [3,4] has minimum-"right" start point. |
| 37 | +# |
| 38 | +# Definition for an interval. |
| 39 | +# class Interval(object): |
| 40 | +# def __init__(self, s=0, e=0): |
| 41 | +# self.start = s |
| 42 | +# self.end = e |
| 43 | + |
| 44 | +class Solution(object): |
| 45 | + def findRightInterval(self, intervals): |
| 46 | + """ |
| 47 | + :type intervals: List[Interval] |
| 48 | + :rtype: List[int] |
| 49 | + """ |
| 50 | + sorted_intervals = sorted((interval.start, i) for i, interval in enumerate(intervals)) |
| 51 | + result = [] |
| 52 | + for interval in intervals: |
| 53 | + idx = bisect.bisect_left(sorted_intervals, (interval.end,)) |
| 54 | + result.append(sorted_intervals[idx][1] if idx < len(sorted_intervals) else -1) |
| 55 | + return result |
0 commit comments