File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=56 lang=javascript
3
+ *
4
+ * [56] 合并区间
5
+ *
6
+ * 1. 将区间排序, 小的在前面
7
+ * 2. 记录当前区间, 对于每一项, 先判断是否与区间相连
8
+ * 3. 相连且右侧值更大则拼接, 否则忽略
9
+ * 4. 不相连则将上一个区间存起来, 该区间作为新当前区间
10
+ */
11
+
12
+ // @lc code=start
13
+ /**
14
+ * @param {number[][] } intervals
15
+ * @return {number[][] }
16
+ */
17
+ var merge = function ( intervals ) {
18
+ if ( intervals . length <= 1 ) {
19
+ return intervals ;
20
+ }
21
+
22
+ intervals . sort ( ( a , b ) => {
23
+ if ( a [ 0 ] < b [ 0 ] ) {
24
+ return - 1 ;
25
+ } else if ( a [ 0 ] > b [ 0 ] ) {
26
+ return 1 ;
27
+ } else {
28
+ if ( a [ 1 ] <= b [ 1 ] ) {
29
+ return - 1 ;
30
+ } else {
31
+ return 1 ;
32
+ }
33
+ }
34
+ } ) ;
35
+
36
+ let result = [ ] ;
37
+ let current = intervals [ 0 ] ;
38
+ for ( let i = 1 ; i < intervals . length ; i ++ ) {
39
+ if ( intervals [ i ] [ 0 ] <= current [ 1 ] ) {
40
+ if ( intervals [ i ] [ 1 ] > current [ 1 ] ) {
41
+ current [ 1 ] = intervals [ i ] [ 1 ] ;
42
+ }
43
+ } else {
44
+ result . push ( current ) ;
45
+ current = intervals [ i ] ;
46
+ }
47
+ }
48
+
49
+ result . push ( current ) ;
50
+ return result ;
51
+ } ;
52
+ // @lc code=end
53
+
You can’t perform that action at this time.
0 commit comments