Skip to content

Commit e8d8120

Browse files
authored
Create 56-merge-intervals.js
1 parent ff4038d commit e8d8120

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

56-merge-intervals.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Definition for an interval.
3+
* function Interval(start, end) {
4+
* this.start = start;
5+
* this.end = end;
6+
* }
7+
*/
8+
/**
9+
* @param {Interval[]} intervals
10+
* @return {Interval[]}
11+
*/
12+
const merge = function(intervals) {
13+
const hash = {}
14+
intervals.forEach(el => {
15+
if (hash.hasOwnProperty(el.start)) {
16+
hash[el.start][1] = Math.max(hash[el.start][1], el.end)
17+
} else {
18+
hash[el.start] = [el.start, el.end]
19+
}
20+
})
21+
22+
const startArr = Object.keys(hash).sort((a, b) => +a - +b)
23+
const res = []
24+
25+
while(startArr.length) {
26+
let start = startArr.shift()
27+
let end = hash[start][1]
28+
29+
for(let i = 0; i < startArr.length; ) {
30+
if (+startArr[i] <= end) {
31+
end = Math.max(end, hash[startArr[i]][1])
32+
startArr.shift()
33+
} else {
34+
break
35+
}
36+
}
37+
let ins = new Interval(+start, end)
38+
res.push(ins)
39+
40+
}
41+
return res
42+
};

0 commit comments

Comments
 (0)