Skip to content

Commit

Permalink
Add scala solution for 56-Merge-Intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisKheng committed Jul 17, 2022
1 parent 8d8db14 commit dd6e023
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions scala/56-Merge-Intervals.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import scala.collection.mutable.ArrayBuffer

object Solution {
def merge(intervals: Array[Array[Int]]): Array[Array[Int]] = {
val (start, end) = (0, 1)
val sortedIntervals = intervals.sortBy(_(start))
val res = ArrayBuffer[Array[Int]](sortedIntervals(0))

for (i <- 1 until sortedIntervals.length) {
val currEndIdx = res.size - 1
val currEnd = res(currEndIdx)
val curr = sortedIntervals(i)

if (currEnd(end) < curr(start)) {
res += curr
} else {
res(currEndIdx)(end) = currEnd(end).max(curr(end))
}
}

return res.toArray
}
}

0 comments on commit dd6e023

Please sign in to comment.