• 1288. Remove Covered Intervals (M)


    Remove Covered Intervals (M)

    题目

    Given a list of intervals, remove all intervals that are covered by another interval in the list.

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

    After doing so, 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
    

    Example 3:

    Input: intervals = [[0,10],[5,12]]
    Output: 2
    

    Example 4:

    Input: intervals = [[3,10],[4,10],[5,11]]
    Output: 2
    

    Example 5:

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

    Constraints:

    • 1 <= intervals.length <= 1000
    • intervals[i].length == 2
    • 0 <= intervals[i][0] < intervals[i][1] <= 10^5
    • All the intervals are unique.

    题意

    删除数组中所有被其他区间覆盖的区间。

    思路

    将数组按照左端点从小到大排序(相同则右端点大的在前),从左到右遍历,记录右端点的最大值rightMax,如果当前区间的右端点小于rightMax,说明该区间被之前的某个区间覆盖,将其删去;否则更新rightMax。


    代码实现

    Java

    class Solution {
        public int removeCoveredIntervals(int[][] intervals) {
            int cnt = 0;
            Arrays.sort(intervals, (int[] a, int[] b) -> a[0] < b[0] ? -1 : a[0] == b[0] ? b[1] - a[1] : 1);
            int rightMax = intervals[0][1];
            for (int i = 1; i < intervals.length; i++) {
                if (intervals[i][1] <= rightMax) {
                    cnt++;
                } else {
                    rightMax = intervals[i][1];
                }
            }
            return intervals.length - cnt;
        }
    }
    
  • 相关阅读:
    golang模板语法简明教程(后面有福利哦)
    C#实现jQuery的方法连缀
    静态构造函数
    MVC4 中使用 Area 和 注意的地方
    APS.NET MVC4生成解析二维码简单Demo
    net mvc 利用NPOI导入导出excel
    Ambari DataNode Start Failure
    Java的三种代理模式
    清理ambari安装的hadoop集群
    【小型系统】简单的刷票系统(突破IP限制进行投票)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13768776.html
Copyright © 2020-2023  润新知