no
04/18/2020, 11:02 AMno
04/18/2020, 11:03 AMJakub Pi
04/18/2020, 4:48 PMfun unionOfIntervals(intervals : List<Pair<Int,Int>>) : List<Pair<Int,Int>> {
fun merge(l : Pair<Int, Int>, r : Pair<Int, Int>) : Pair<Int, Int> = Pair(min(l.first, r.first), max(l.second, r.second))
val sortedIntervals = intervals.sortedBy { it.first }
return sortedIntervals.fold(mutableListOf<Pair<Int,Int>>()) { acc, pair ->
when {
acc.isEmpty() -> mutableListOf(pair)
acc.last().second >= pair.first -> acc.apply { this[acc.size-1] = merge(acc.last(), pair)}
else -> acc.apply { add(pair) }
}
}
}
no
04/18/2020, 4:58 PMno
04/18/2020, 4:58 PMJakub Pi
04/18/2020, 5:03 PM.sumBy { it.second - it.first }
to the call :)no
04/18/2020, 6:08 PMnkiesel
04/20/2020, 7:12 PM4
is not in your result, is it? So result should really be [1,3],[5],[8,9]]
. And assuming we are talking about closed intervals here, you need `.sumBy { it.second - it.first + 1}`no
04/21/2020, 4:06 PMJakub Pi
04/23/2020, 6:51 AM