File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments