在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ An integer interval Find the minimum size of a set S such that for every integer interval A in 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:
一个整数区间 给你一组整数区间 输出这个最小集合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}. 注意:
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 }
|
请发表评论