715. Range Module
Problem description:
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.
A half-open interval [left, right)
denotes all the real numbers x
where left <= x < right
.
Implement the RangeModule
class:
RangeModule()
Initializes the object of the data structure.void addRange(int left, int right)
Adds the half-open interval[left, right)
, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval[left, right)
that are not already tracked.boolean queryRange(int left, int right)
Returnstrue
if every real number in the interval[left, right)
is currently being tracked, andfalse
otherwise.void removeRange(int left, int right)
Stops tracking every real number currently being tracked in the half-open interval[left, right)
.
Example 1:
1 | Input |
Constraints:
1 <= left < right <= 109
- At most
104
calls will be made toaddRange
,queryRange
, andremoveRange
.
Solution:
原本紀錄區間是[(1,2),(3,5),(8,12)]
但可改為紀錄是:[1,2,3,5,8,12]
经过这样的处理, 数组的奇数坐标就是区间的结束点,偶数坐标就是开始点
Example:
1 | addRange(10, 20) -> [10, 20] |
1 | class RangeModule: |
time complexity:
addRange: $O(n)$
removeRange: $O(n)$
queryRange: $O(logn)$
space complexity: $O()$
reference:
related problem: