[Swift]LeetCode352. 将数据流变为多个不相交间隔 | Data Stream as Disjoint Intervals
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10275923.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.
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:
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,…,将到目前为止看到的数字总结为不相交的间隔列表。
例如,假设数据流中的整数为 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了