LeetCode 436. Find Right Interval

You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.

The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.

Return an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.

Example 1:

Input: intervals = [[1,2]]
Output: [-1]
Explanation: There is only one interval in the collection, so it outputs -1.

Example 2:

Input: intervals = [[3,4],[2,3],[1,2]]
Output: [-1,0,1]
Explanation: There is no right interval for [3,4].
The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.
The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.

Example 3:

Input: intervals = [[1,4],[2,3],[3,4]]
Output: [-1,2,-1]
Explanation: There is no right interval for [1,4] and [3,4].
The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.

Constraints:

  • 1 <= intervals.length <= 2 * 104
  • intervals[i].length == 2
  • -106 <= starti <= endi <= 106
  • The start point of each interval is unique.

其实思路挺直观的,因为要找每个interval里end对应的最接近的下一个start值,所以dependency没有很多,可以直接采用一个treemap记录start和它对应的index,直接在treemap里采用built in的ceilingEntry进行查找。

Runtime: 43 ms, faster than 56.69% of Java online submissions for Find Right Interval.

Memory Usage: 57.7 MB, less than 11.43% of Java online submissions for Find Right Interval.

class Solution {
    public int[] findRightInterval(int[][] intervals) {
        int[] result = new int[intervals.length];
        
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < intervals.length; i++) {
            map.put(intervals[i][0], i);
        }
        
        for (int i = 0; i < intervals.length; i++) {
            Map.Entry<Integer, Integer> ceilingEntry = map.ceilingEntry(intervals[i][1]);
            if (ceilingEntry != null) {
                result[i] = ceilingEntry.getValue();
            } else {
                result[i] = -1;
            }
        }
        
        return result;
    }
}

如果不用treemap的话,可以用一个hashmap存start和对应的index,然后用一个数组存start并sort它,然后采用binary search的方法来查找最小的>= end的start值,回到hashmap里找下标。先不写解法了,以后有空回来写。https://leetcode.com/problems/find-right-interval/discuss/631133/Java-O(n-logn)-solution-HashMap-%2B-Sort-%2B-Binary-Search

还有人用了两个heap来做,好像也合理,但没仔细看:Loading...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值