在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals. For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be: [1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7] Follow up: 给定一个非负整数的数据流输入 a1,a2,…,an,…,将到目前为止看到的数字总结为不相交的间隔列表。 例如,假设数据流中的整数为 1,3,7,2,6,…,每次的总结为: [1, 1] [1, 1], [3, 3] [1, 1], [3, 3], [7, 7] [1, 3], [7, 7] [1, 3], [6, 7] 进阶: 412ms 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
|
请发表评论