File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ import "sort"
2
+
3
+ func merge (intervals [][]int ) [][]int {
4
+ const (
5
+ start = 0
6
+ end = 1
7
+ )
8
+
9
+ sort .SliceStable (intervals , func (i , j int ) bool {
10
+ return intervals [i ][start ] < intervals [j ][start ]
11
+ })
12
+
13
+ res := [][]int {intervals [0 ]}
14
+ for i := 1 ; i < len (intervals ); i ++ {
15
+ currResLastIndex := len (res ) - 1
16
+ currEnd := res [currResLastIndex ]
17
+ curr := intervals [i ]
18
+
19
+ if currEnd [end ] < curr [start ] {
20
+ res = append (res , curr )
21
+ } else if currEnd [end ] < curr [end ] {
22
+ res [currResLastIndex ][end ] = curr [end ]
23
+ }
24
+ }
25
+
26
+ return res
27
+ }
Original file line number Diff line number Diff line change
1
+ import scala .collection .mutable .ArrayBuffer
2
+
3
+ object Solution {
4
+ def merge (intervals : Array [Array [Int ]]): Array [Array [Int ]] = {
5
+ val (start, end) = (0 , 1 )
6
+ val sortedIntervals = intervals.sortBy(_(start))
7
+ val res = ArrayBuffer [Array [Int ]](sortedIntervals(0 ))
8
+
9
+ for (i <- 1 until sortedIntervals.length) {
10
+ val currEndIdx = res.size - 1
11
+ val currEnd = res(currEndIdx)
12
+ val curr = sortedIntervals(i)
13
+
14
+ if (currEnd(end) < curr(start)) {
15
+ res += curr
16
+ } else {
17
+ res(currEndIdx)(end) = currEnd(end).max(curr(end))
18
+ }
19
+ }
20
+
21
+ return res.toArray
22
+ }
23
+ }
You can’t perform that action at this time.
0 commit comments