leetcode 1288. Remove Covered Intervals(去掉重叠的区间)

Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.

The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.

Return the number of remaining intervals.

Example 1:

Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:

Input: intervals = [[1,4],[2,3]]
Output: 1

给出二维数组,里面每一个元素都是一个区间,返回一共有多少个不重叠的区间。
区间重叠是指起点和终点覆盖了另一个区间。

思路:
因为区间重叠是指
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
按区间的起点大小排序,这样就满足了c <= a,只需要看终点b <= d
当然终点要从大往小看,因为先看大的,后面的比它小,就是在一个区间里。遇见比当前大的终点,就说明是一个新的区间。

    public int removeCoveredIntervals(int[][] intervals) {
        int result = 0;
        int end = -1;
        int n = intervals.length;
        
        //按起点大小升序排序,如果起点大小相同,按终点降序排序
        Arrays.sort(intervals, (o1, o2)->o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0]);
        
        for(int[] interval : intervals) {
            if(end < interval[1]) {
                result ++;
                end = interval[1];
            }
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值