Skip to content

Commit dda0512

Browse files
authored
Update 715-range-module.js
1 parent bd78e50 commit dda0512

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

715-range-module.js

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,87 @@ RangeModule.prototype.removeRange = function (left, right) {
198198
* var param_2 = obj.queryRange(left,right)
199199
* obj.removeRange(left,right)
200200
*/
201+
202+
// another
203+
204+
const RangeModule = function () {
205+
this.intervals = []
206+
}
207+
208+
/**
209+
* @param {number} left
210+
* @param {number} right
211+
* @return {void}
212+
*/
213+
RangeModule.prototype.addRange = function (left, right) {
214+
const tmp = []
215+
const n = this.intervals.length
216+
for(let i = 0; i <= n; i++) {
217+
const cur = this.intervals[i]
218+
if(i === n || cur[0] > right) {
219+
tmp.push([left, right])
220+
while(i < n) tmp.push(this.intervals[i++])
221+
}else if(cur[1] < left) {
222+
tmp.push(cur)
223+
}else {
224+
// cur[0] <= right
225+
// left <= cur[1]
226+
left = Math.min(left, cur[0])
227+
right = Math.max(right, cur[1])
228+
}
229+
}
230+
// console.log(tmp)
231+
this.intervals = tmp
232+
}
233+
234+
/**
235+
* @param {number} left
236+
* @param {number} right
237+
* @return {boolean}
238+
*/
239+
RangeModule.prototype.queryRange = function (left, right) {
240+
const n = this.intervals.length, arr = this.intervals
241+
let l = 0, r = n - 1
242+
while(l <= r) {
243+
const mid = ~~(l + (r - l) / 2)
244+
if(arr[mid][0] >= right) r = mid - 1
245+
else if(arr[mid][1] <= left) l = mid + 1
246+
else return arr[mid][0] <= left && arr[mid][1] >= right
247+
}
248+
249+
return false
250+
}
251+
252+
/**
253+
* @param {number} left
254+
* @param {number} right
255+
* @return {void}
256+
*/
257+
RangeModule.prototype.removeRange = function (left, right) {
258+
const tmp = []
259+
const n = this.intervals.length
260+
261+
for(let i = 0; i < n; i++) {
262+
const cur = this.intervals[i]
263+
if(cur[1] < left) {
264+
tmp.push(cur)
265+
}else if(cur[0] > right) tmp.push(cur)
266+
else {
267+
// left <= cur[1]
268+
// cur[0] <= right
269+
if(left > cur[0]) tmp.push([cur[0], left])
270+
if(right < cur[1]) tmp.push([right, cur[1]])
271+
}
272+
}
273+
// console.log(tmp)
274+
this.intervals = tmp
275+
}
276+
277+
/**
278+
* Your RangeModule object will be instantiated and called as such:
279+
* var obj = new RangeModule()
280+
* obj.addRange(left,right)
281+
* var param_2 = obj.queryRange(left,right)
282+
* obj.removeRange(left,right)
283+
*/
284+

0 commit comments

Comments
 (0)