Skip to content

Commit c70be8f

Browse files
authored
Merge pull request #514 from ChrisKheng/main
Add scala and go solution for 56-Merge-Intervals
2 parents e95a2ad + 77ae395 commit c70be8f

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

go/56-Merge-Intervals.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

scala/56-Merge-Intervals.scala

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}

0 commit comments

Comments
 (0)