forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 12
/
MergeIntervals.scala
42 lines (31 loc) · 1.04 KB
/
MergeIntervals.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package algorithms.array
import scala.collection.mutable.ListBuffer
case class Interval(start: Int, end: Int) extends Ordered[Interval] {
override def compare(that: Interval): Int =
if (this.start == that.start)
this.end compare that.end
else
this.start compare that.start
}
object MergeIntervals {
implicit def listToInterval(list: List[Int]): Interval = Interval(list.head, list.apply(1))
implicit def tupleToInterval(tuple: (Int, Int)): Interval = Interval(tuple._1, tuple._2)
def apply(intervals: List[Interval]): List[Interval] = {
var merged = ListBuffer.empty[Interval]
val sorted = intervals.sorted
sorted.zipWithIndex.foreach(zipped => {
val (interval, i) = zipped
if(i > 0) {
val prevInterval = sorted.apply(i - 1)
if(prevInterval.end >= interval.start) {
merged = merged.updated(i - 1, Interval(prevInterval.start, interval.end))
} else {
merged += interval
}
} else {
merged += interval
}
})
merged.toList
}
}