[Swift]LeetCode757.设置交集大小至少为2 | Set Intersection Size At Least Two

it2022-05-06  5

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址: https://www.cnblogs.com/strengthen/p/10532897.html ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from ato 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 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。

给你一组整数区间intervals,请找到一个最小的集合 S,使得 S 里的元素与区间intervals中的每一个整数区间都至少有2个元素相交。

输出这个最小集合S的大小。

示例 1:

输入: 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]范围内的整数。
Runtime: 252 ms Memory Usage: 19.1 MB 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 }

 

转载于:https://www.cnblogs.com/strengthen/p/10532897.html

相关资源:DirectX修复工具V4.0增强版

最新回复(0)