在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.
Example 1: addRange(10, 20): null removeRange(14, 16): null queryRange(10, 14): true (Every number in [10, 14) is being tracked) queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation) Note:
Range 模块是跟踪数字范围的模块。你的任务是以一种有效的方式设计和实现以下接口。
示例: addRange(10, 20): null removeRange(14, 16): null queryRange(10, 14): true (区间 [10, 14) 中的每个数都正在被跟踪) queryRange(13, 15): false (未跟踪区间 [13, 15) 中像 14, 14.03, 14.17 这样的数字) queryRange(16, 17): true (尽管执行了删除操作,区间 [16, 17) 中的数字 16 仍然会被跟踪) 提示:
Runtime: 2188 ms
Memory Usage: 20.9 MB
1 class RangeModule { 2 var v:[(Int,Int)] 3 4 init() { 5 v = [(Int,Int)]() 6 } 7 8 func addRange(_ left: Int, _ right: Int) { 9 var left = left 10 var right = right 11 var res:[(Int,Int)] = [(Int,Int)]() 12 var n:Int = v.count 13 var cur:Int = 0 14 for i in 0..<n 15 { 16 if v[i].1 < left 17 { 18 res.append(v[i]) 19 cur += 1 20 } 21 else if v[i].0 > right 22 { 23 res.append(v[i]) 24 } 25 else 26 { 27 left = min(left, v[i].0) 28 right = max(right, v[i].1) 29 } 30 } 31 res.insert((left, right),at:cur) 32 v = res 33 } 34 35 func queryRange(_ left: Int, _ right: Int) -> Bool { 36 for a in v 37 { 38 if a.0 <= left && a.1 >= right 39 { 40 return true 41 } 42 } 43 return false 44 } 45 46 func removeRange(_ left: Int, _ right: Int) { 47 var res:[(Int,Int)] = [(Int,Int)]() 48 var t:[(Int,Int)] = [(Int,Int)]() 49 var n:Int = v.count 50 var cur:Int = 0 51 for i in 0..<n 52 { 53 if v[i].1 <= left 54 { 55 res.append(v[i]) 56 cur += 1 57 } 58 else if v[i].0 >= right 59 { 60 res.append(v[i]) 61 } 62 else 63 { 64 if v[i].0 < left 65 { 66 t.append((v[i].0, left)) 67 } 68 if v[i].1 > right 69 { 70 t.append((right, v[i].1)) 71 } 72 } 73 } 74 res += t 75 v = res 76 } 77 } 78 79 /** 80 * Your RangeModule object will be instantiated and called as such: 81 * let obj = RangeModule() 82 * obj.addRange(left, right) 83 * let ret_2: Bool = obj.queryRange(left, right) 84 * obj.removeRange(left, right) 85 */
|
请发表评论