Find Right Interval

https://leetcode.com/problems/find-right-interval/description/

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:

  1. You may assume the interval's end point is always bigger than its start point.

  2. You may assume none of these intervals have the same start point.

Thoughts

和heaters异曲同工。只不过这次sort的目标换成了interval, 需要自己实现下Comparator. 然后遍历intervals查找排好序的离该interval.end比它的最近的start是哪个。注意由于对返回的顺序有要求,因此要备份下位置。

Code

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
class Solution {
    private int binSearch(Interval[] intervals, int target) {
        int start = 0, end = intervals.length - 1;
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (intervals[mid].start < target) {
                start = mid + 1;
            } else {
                end = mid;
            }
        }

        if (intervals[start].start >= target) {
            return start;
        }
        return -1;
    }


    public int[] findRightInterval(Interval[] intervals) {
        Map<Interval, Integer> locs = new HashMap<>();
        Interval[] tmp = new Interval[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            locs.put(intervals[i], i);
            tmp[i] = intervals[i];
        }
        Arrays.sort(tmp, (a, b) -> a.start == b.start ? a.end - b.end : a.start - b.start);
        int[] res = new int[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            int tpos = binSearch(tmp, intervals[i].end);
            if (tpos != -1) {
                res[i] = locs.get(tmp[tpos]);
            } else {
                res[i] = -1;
            }
        }
        return res;
    }
}

Analysis

时间复杂度为O(nlgn).

Last updated