0
1:添加範圍 - 跟蹤提供的輸入範圍。添加與當前跟蹤範圍部分重疊的範圍應跟蹤添加範圍中尚未跟蹤的任何數字。設計並實現使用python跟蹤範圍的界面
e.g. AddRange(10,180)- start tracking range 10-180
AddRange(150,200)- start tracking range 150-200
AddRange(250,500) - start tracking range 250-500
可能的解決方法
def merge_ranges(ranges):
ranges = iter(sorted(ranges))
current_start, current_stop = next(ranges)
for start, stop in ranges:
if start > current_stop:
# Gap between segments: output current segment and start a new one.
yield current_start, current_stop
current_start, current_stop = start, stop
else:
# Segments adjacent or overlapping: merge.
current_stop = max(current_stop, stop)
yield current_start, current_stop
2:刪除範圍:從那些被臨時固定刪除號碼的供給範圍。部分跟蹤範圍的刪除範圍操作應刪除已經跟蹤的範圍內的所有數字。
e.g. Ranges tracked [10-200],[250-500]
RemoveRange(50,150) - stop tracking range 50-150 ([10-149], [151-200],[250-500])
RemoveRange(400,600) - stop tracking range 400-500 ([10-49],[250-399])
Remove range(600,800) - no-op as none of the ranges were tracked
可能的解決方法
def remove_overlap(rs):
rs.sort()
def process (rs,deviation):
start = len(rs) - deviation - 1
if start < 1:
return rs
if rs[start][0] > rs[start-1][1]:
return process(rs,deviation+1)
else:
rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] < rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] > rs[start][1]])
del rs[start]
return process(rs,0)
return process(rs,0)
3查詢範圍:如果整個範圍被追蹤返回true;否則爲假
e.g QueryRange(50,100) - returns True
QueryRange(180,300) - returns False (only part of the range is being tracked)
QueryRange (600,100)- returns False(not tracked at all)
如何到執行此操作?
此外,需要實現面向對象的方式,整個事情:
僞代碼:
class RangeModule:
def AddRange(self, lower, upper):
pass
def QueryRange(self, lower, upper):
return True
def RemoveRange(self, lower, upper):
pass