一、题目描述
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:
intervals
will have length in range[1, 3000]
.intervals[i]
will have length2
, representing some integer interval.intervals[i][j]
will be an integer in[0, 10^8]
.
二、题目分析
依题意,我们需要求出一个 最小 集合 S
,使得 S
中至少有两个数落在 intervals
中给出的每个闭区间中,即 S
与intervals
中给出的每个闭区间的交集的元素个数大于等于 2。最后返回该集合 S
的元素个数。
这里我们可以考虑从“最初”开始构建这样的一个集合。将 intervals
中的区间按照右端点的升序进行排序,若右端点相等,则以左端点的降序进行排序(原因说明在之后)。将排序后的一个区间的最后两个整数首先加入 S
中,作为“最初”的情况,之后再遍历处理剩下的区间。
在遍历到某一个区间 I
时,此时的 S
应能满足排在该区间之前的所有区间,在这样的前提下我们来处理这个区间 I
。简单来看,只需判断 ∣ I ∩ S ∣ | I∩S | ∣I∩S∣ 的大小即可。
- 若等于 2,则说明可以满足条件,无需再添加数字到
S
中。 - 若等于 1,则我们还需要从
I
中选择一个整数添加到S
中,使得它们交集的元素个数大于2,那么显然,我们选择I
中的最后一个整数,这也是我们按右端点升序排序的原因——这既能使得 ∣ I ∩ S ∣ = 2 | I∩S | = 2