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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 ato 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

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

一個整數區間 [a, b]  ( a < b ) 表明着從 a 到 b 的全部連續整數,包括 a 和 bspa

給你一組整數區間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}.

注意:

  1. intervals 的長度範圍爲[1, 3000]
  2. intervals[i] 長度爲 2,分別表明左、右邊界。
  3. 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 }
相關文章
相關標籤/搜索