Leetcode 1288. Remove Covered Intervals (区间好题)

  1. Remove Covered Intervals
    Medium
    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

Constraints:

1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= li < ri <= 105
All the given intervals are unique.

解法1:先把left和right设为intervals[0]的边界,然后再分1) cover 2) overlap 3) 无重合 3种情况处理。

struct cmp {
    bool operator () (const vector<int> &a, const vector<int> &b) {
        if (a[0] <= b[0]) return true;
        if (a[0] == b[0]) return a[1] < b[1];
        return false;
    }
};

class Solution {
public:
    int removeCoveredIntervals(vector<vector<int>>& intervals) {
        int n = intervals.size();
        if (n == 0) return 0;
        sort(intervals.begin(), intervals.end(), cmp()); //sort的第3个参数要么是function(),要么是类或结构的实例!但priority_queue的第3个参数是类或结构的定义!
        //sort(intervals.begin(), intervals.end(), [](const auto &a, const auto &b){ return a[0] < b[0];}); //写成这样更简练
        int left = intervals[0][0] , right = intervals[0][1];
        int res = 0;
        for (int i = 1; i < n; i++) {
            if (left <= intervals[i][0] && right >= intervals[i][1]) { //case 1: cover
                res++;
            } else if (left < intervals[i][1] && right > intervals[i][0]) { //case 2: overlap
                left = min(left, intervals[i][0]);
                right = max(right, intervals[i][1]);
            } else { //case 3: no cover or overlap
                left = intervals[i][0];
                right = intervals[i][1];
            }
        }
        return n - res;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)