★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-upldawby-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
An integer interval [a, b]
(for integers a < b
) is a set of all consecutive integers from a
to b
, including a
and b
.git
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.github
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:ide
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:this
intervals
will have length in range [1, 3000]
.intervals[i]
will have length 2
, representing some integer interval.intervals[i][j]
will be an integer in [0, 10^8]
.一个整数区间 [a, b]
( a < b
) 表明着从 a
到 b
的全部连续整数,包括 a
和 b
。spa
给你一组整数区间intervals
,请找到一个最小的集合 S,使得 S 里的元素与区间intervals
中的每个整数区间都至少有2个元素相交。code
输出这个最小集合S的大小。htm
示例 1:blog
输入: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]] 输出: 3 解释: 考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。 且这是S最小的状况,故咱们输出3。
示例 2:
输入: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]] 输出: 5 解释: 最小的集合S = {1, 2, 3, 4, 5}.
注意:
intervals
的长度范围为[1, 3000]
。intervals[i]
长度为 2
,分别表明左、右边界。intervals[i][j]
的值是 [0, 10^8]
范围内的整数。1 class Solution { 2 func intersectionSizeTwo(_ intervals: [[Int]]) -> Int { 3 var intervals = intervals 4 var res:Int = 0 5 var p1:Int = -1 6 var p2:Int = -1 7 intervals.sort(by:{(a:[Int],b:[Int]) -> Bool in 8 return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0])}) 9 for interval in intervals 10 { 11 if interval[0] <= p1 {continue} 12 if interval[0] > p2 13 { 14 res += 2 15 p2 = interval[1] 16 p1 = p2 - 1 17 } 18 else 19 { 20 res += 1 21 p1 = p2 22 p2 = interval[1] 23 } 24 } 25 return res 26 } 27 }