-
Notifications
You must be signed in to change notification settings - Fork 4
/
merge-intervals.js
86 lines (78 loc) · 1.96 KB
/
merge-intervals.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var DEBUG = process.env.DEBUG;
function Node(st, ed) {
this.st = st;
this.ed = ed;
if (ed - st > 1) {
this.l = new Node(st, (st+ed) >> 1);
this.r = new Node((st+ed) >> 1, ed);
} else if (ed - st === 1) {
this.l = new Node(st, st);
this.r = new Node(ed, ed);
}
this.c = false;
}
Node.prototype.cover = function (st, ed) {
if (st > ed) return;
if (this.c) return ;
if (this.st >= st && this.ed <= ed) {
this.c = true;
return ;
}
if ((ed <= this.st && st < this.st) || (st >= this.ed && ed > this.ed))
return ;
if (this.l) this.l.cover(st, ed);
if (this.r) this.r.cover(st, ed);
return ;
};
function dfs(tree, result) {
if (!tree) return;
if (tree.c) {
if (result.length && result[result.length - 1].end === tree.st) {
result[result.length - 1].end = tree.ed;
} else {
result.push(new Interval(tree.st, tree.ed));
}
} else {
dfs(tree.l, result);
dfs(tree.r, result);
}
}
function Interval(start, end) {
this.start = start;
this.end = end;
}
Interval.prototype.toArray = function () {
return [this.start, this.end];
};
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
var merge = function(intervals) {
var left = Math.min.apply(undefined, intervals.map(i => i.start));
var right = Math.max.apply(undefined, intervals.map(i => i.end));
var tree = new Node(left, right);
intervals.forEach(i => tree.cover(i.start, i.end));
var result = [];
dfs(tree, result);
return result.map(function (i) {
return i.toArray();
});
};
function buildInterval(array) {
return new Interval(array[0], array[1]);
}
function test(f) {
[
[ [1,3], [2, 6], [8, 10], [15, 18]],
[ [1, 3] ],
[ [0, 0] ],
[ [0, 0], [2, 2] ],
[ [0, 0], [2, 2], [2, 7] ],
[ [0, 0], [5, 5], [0, 8] ],
].forEach(function (input) {
input = input.map(buildInterval);
console.log(f.call(undefined, input).map(i => i.toArray ? i.toArray() : i ));
});
}
if (DEBUG) test(merge);