[Leetcode] 757. Set Intersection Size At Least Two 解题报告

题目

An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b.

Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has size at least 2.

Example 1:

Input: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
Output: 3
Explanation:
Consider the set S = {2, 3, 4}.  For each interval, there are at least 2 elements from S in the interval.
Also, there isn't a smaller size set that fulfills the above condition.
Thus, we output the size of this set, which is 3.

Example 2:

Input: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
Output: 5
Explanation:
An example of a minimum sized set is {1, 2, 3, 4, 5}.

Note:

  1. intervals will have length in range [1, 3000].
  2. intervals[i] will have length 2, representing some integer interval.
  3. intervals[i][j] will be an integer in [0, 10^8].

思路

我们首先根据intervals的尾节点大小对intervals进行排序:尾节点越靠前的interval越排到前面。然后定义两个交点p1和p2(p1 < p2),并遍历排序后的intervals,遍历过程中会出现如下三种情况:

1)如果intervals[i]在p1的左侧,那么说明p1和p2一定都和intervals相交(为什么可以保证p2也和intervals[i]相交呢?参考排序规则),所以我们就不需要做什么了;

2)如果intervals[i]在p2的右侧,那么说明p1和p2都没有和intervals相交,所以我们更新ans,并且置p1和p2为intervals[i]上最大的两个整数(因为最大的整数才最有可能在后面和其余的intervals相交);

3)如果intervals[i]在p1和p2之间,那么说明只有p2和intervals相交,所以我们就让p1,p2右移。

算法的时间复杂度为O(nlogn),为排序所花费的时间,空间复杂度为O(1)。

代码

class Solution {
public:
    int intersectionSizeTwo(vector<vector<int>>& intervals) {
        // sort the intervals by their ending points
        sort(intervals.begin(), intervals.end(), [](vector<int> &a, vector<int> &b) {
            return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0]); 
        });
        int ans = 0, p1 = -1, p2 = -1;
        for (int i = 0; i < intervals.size(); ++i) {
            if (intervals[i][0] <= p1) {        // both p1 and p2 intersect with intervals[i]
                continue;
            }
            else if (intervals[i][0] > p2) {    // neither of p1 and p2 intersect with intervals[i]
                ans += 2;
                p2 = intervals[i][1];           // choose the two biggest points
                p1 = p2 - 1;
            }  
            else {                              // only p2 intersects with intervals[i]
                ans += 1;
                p1 = p2;
                p2 = intervals[i][1];
            }
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值