Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

56. Merge Intervals

Topics: Array Sorting

Solution 1

Implementation

class Solution {
    fun merge(intervals: Array<IntArray>): Array<IntArray> {
        val sortedIntervals = intervals.sortedBy { it[0] }
        val mergedIntervals = mutableListOf<IntArray>()
        mergedIntervals.add(sortedIntervals.first())

        for (interval in sortedIntervals) {
            val lastInterval = mergedIntervals.last()
            if (interval[0] > lastInterval[1]) {
                mergedIntervals.add(interval)
            } else {
                val newLastInterval = intArrayOf(
                    min(interval[0], lastInterval[0]),
                    max(interval[1], lastInterval[1])
                )
                mergedIntervals.removeLast()
                mergedIntervals.add(newLastInterval)
            }
        }

        return mergedIntervals.toTypedArray()
    }
}

Solution 2

Implementation

class Solution {
    fun merge(intervals: Array<IntArray>): Array<IntArray> {
        val size = 10001
        val arr = IntArray(size){ -1 }
        var minIndex = intervals[0][0]

        for (interval in intervals) {
            val (start, end) = interval[0] to interval[1]
            arr[start] = max(arr[start], end)
            minIndex = min(minIndex, start)
        }

        val mergedIntervals = mutableListOf<IntArray>()
        var (startIndex, endIndex) = minIndex to arr[minIndex]

        for (i in 0 until size) {
            if (arr[i] == -1) continue
            if (i > endIndex) {
                mergedIntervals.add(intArrayOf(startIndex, endIndex))
                startIndex = i
            }
            endIndex = max(endIndex, arr[i])
        }

        mergedIntervals.add(intArrayOf(startIndex, endIndex))

        return mergedIntervals.toTypedArray()
    }
}