zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    使用Junit对Spring进行单元测试实战小结
    【VBA编程】02.调试VBA程序
    【VBA编程】01.第一个VBA程序Hello world
    VBA验证工作表是否存在
    VBA对指定单元格填充颜色并且赋值
    Excle中range的一些用法
    Debug.print的用法
    EXCLE图形插入实例
    DB2建立不记录日志的表
    Excle快速输入√与×
  • 原文地址:https://www.cnblogs.com/mapoos/p/13768776.html
Copyright © 2011-2022 走看看