★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rbztpleu-cq.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.git
Note:github
Example 1:微信
Input: [ [1,2], [2,3], [3,4], [1,3] ] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:app
Input: [ [1,2], [1,2], [1,2] ] Output: 2 Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:spa
Input: [ [1,2], [2,3] ] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
給定一個區間的集合,找到須要移除區間的最小數量,使剩餘區間互不重疊。rest
注意:code
示例 1:htm
輸入: [ [1,2], [2,3], [3,4], [1,3] ] 輸出: 1 解釋: 移除 [1,3] 後,剩下的區間沒有重疊。
示例 2:blog
輸入: [ [1,2], [1,2], [1,2] ] 輸出: 2 解釋: 你須要移除兩個 [1,2] 來使剩下的區間沒有重疊。
示例 3:
輸入: [ [1,2], [2,3] ] 輸出: 0 解釋: 你不須要移除任何區間,由於它們已是無重疊的了。
76ms
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * public var start: Int 5 * public var end: Int 6 * public init(_ start: Int, _ end: Int) { 7 * self.start = start 8 * self.end = end 9 * } 10 * } 11 */ 12 class Solution { 13 func eraseOverlapIntervals(_ intervals: [Interval]) -> Int { 14 var intervals = intervals 15 if intervals.isEmpty {return 0} 16 intervals.sort(by:{(_ a:Interval,_ b:Interval) -> Bool in return a.start < b.start}) 17 var res:Int = 0 18 var n:Int = intervals.count 19 var endLast:Int = intervals[0].end 20 for i in 1..<n 21 { 22 var t:Int = endLast > intervals[i].start ? 1 : 0 23 endLast = t == 1 ? min(endLast, intervals[i].end) : intervals[i].end 24 res += t 25 } 26 return res 27 } 28 }
80ms
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * public var start: Int 5 * public var end: Int 6 * public init(_ start: Int, _ end: Int) { 7 * self.start = start 8 * self.end = end 9 * } 10 * } 11 */ 12 class Solution { 13 func eraseOverlapIntervals(_ intervals: [Interval]) -> Int { 14 if intervals.count <= 1 { 15 return 0 16 } 17 18 var move = 1 19 var ts = intervals 20 ts.sort { (i1, i2) -> Bool in 21 return i1.end <= i2.end 22 } 23 24 var temp = ts[0] 25 for i in 1..<ts.count { 26 let start = ts[i].start 27 if start >= temp.end { 28 move += 1 29 temp = ts[i] 30 } 31 } 32 return intervals.count - move 33 } 34 }