★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-aovimhlz-gn.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.git
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:github
[1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?微信
給定一個非負整數的數據流輸入 a1,a2,…,an,…,將到目前爲止看到的數字總結爲不相交的間隔列表。app
例如,假設數據流中的整數爲 1,3,7,2,6,…,每次的總結爲:spa
[1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7]
進階:
若是有不少合併,而且與數據流的大小相比,不相交間隔的數量很小,該怎麼辦?code
412mshtm
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 13 class SummaryRanges { 14 var v:[Interval] 15 /** Initialize your data structure here. */ 16 init() { 17 v = [Interval]() 18 } 19 20 func addNum(_ val: Int) { 21 var cur:Interval = Interval(val, val) 22 var res:[Interval] = [Interval]() 23 var pos:Int = 0 24 for a in v 25 { 26 if cur.end + 1 < a.start 27 { 28 res.append(a) 29 } 30 else if cur.start > a.end + 1 31 { 32 res.append(a) 33 pos += 1 34 } 35 else 36 { 37 cur.start = min(cur.start, a.start) 38 cur.end = max(cur.end, a.end) 39 } 40 } 41 res.insert( cur,at: pos) 42 v = res 43 } 44 45 func getIntervals() -> [Interval] { 46 return v 47 } 48 } 49 50 /** 51 * Your SummaryRanges object will be instantiated and called as such: 52 * let obj = SummaryRanges() 53 * obj.addNum(val) 54 * let ret_2: [Interval] = obj.getIntervals() 55 */ 56