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;
        }
    }
    
  • 相关阅读:
    poj 2584 T-Shirt Gumbo (二分匹配)
    hdu 1757 A Simple Math Problem (乘法矩阵)
    矩阵之矩阵乘法(转载)
    poj 2239 Selecting Courses (二分匹配)
    hdu 3661 Assignments (贪心)
    hdu 1348 Wall (凸包)
    poj 2060 Taxi Cab Scheme (二分匹配)
    hdu 2202 最大三角形 (凸包)
    hdu 1577 WisKey的眼神 (数学几何)
    poj 1719 Shooting Contest (二分匹配)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13768776.html
Copyright © 2011-2022 走看看