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].

 


 

二、题目分析

  依题意,我们需要求出一个 最小 集合 S ,使得 S 中至少有两个数落在 intervals 中给出的每个闭区间中,即 Sintervals 中给出的每个闭区间的交集的元素个数大于等于 2。最后返回该集合 S 的元素个数。

  这里我们可以考虑从“最初”开始构建这样的一个集合。将 intervals 中的区间按照右端点的升序进行排序,若右端点相等,则以左端点的降序进行排序(原因说明在之后)。将排序后的一个区间的最后两个整数首先加入 S 中,作为“最初”的情况,之后再遍历处理剩下的区间。
  在遍历到某一个区间 I 时,此时的 S 应能满足排在该区间之前的所有区间,在这样的前提下我们来处理这个区间 I。简单来看,只需判断 ∣ I ∩ S ∣ | I∩S | IS 的大小即可。

  • 若等于 2,则说明可以满足条件,无需再添加数字到 S 中。
  • 若等于 1,则我们还需要从 I 中选择一个整数添加到 S 中,使得它们交集的元素个数大于2,那么显然,我们选择 I 中的最后一个整数,这也是我们按右端点升序排序的原因——这既能使得 ∣ I ∩ S ∣ = 2 | I∩S | = 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值