-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0056-MergeIntervals.js
More file actions
47 lines (41 loc) · 1.16 KB
/
0056-MergeIntervals.js
File metadata and controls
47 lines (41 loc) · 1.16 KB
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
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 38.8 MB
// Link: https://leetcode.com/submissions/detail/385391748/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
var merge = function(intervals) {
if (intervals.length <= 1) {
return intervals;
}
intervals.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
let results = [];
let prev = intervals[0];
for (let current of intervals) {
if (prev[1] >= current[0]) {
prev[1] = Math.max(current[1], prev[1]);
} else {
results.push(prev);
prev = current;
}
}
results.push(prev);
return results;
};
return {
merge: merge
};
};
module.exports = solution();