LeetCode之Insert Interval(Kotlin)

嘟囔發表於2019-03-26

問題: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
複製程式碼

方法: 先建立結果list,然後新增newInterval作為基準,然後遍歷intervals所有元素,區間在newInterval左邊的區間add到左邊,區間在newInterval右邊的區間add到右邊,如果區間有交疊則與newInterval做合併,最後遍歷結束即為結果。

具體實現:

class InsertInterval {
    // Definition for an interval.
    class Interval(var start: Int = 0, var end: Int = 0) {
        override fun toString(): String {
            return "Interval(start=$start, end=$end)"
        }
    }

    fun insert(intervals: List<Interval>, newInterval: Interval): List<Interval> {
        val result = mutableListOf<Interval>()
        result.add(newInterval)
        for (interval in intervals) {
            if (interval.end < newInterval.start) {
                result.add(result.lastIndex, interval)
            } else if (interval.start > newInterval.end) {
                result.add(result.lastIndex+1, interval)
            } else if (interval.start <= newInterval.start && interval.end >= newInterval.end ) {
                newInterval.start = interval.start
                newInterval.end = interval.end
            } else if (interval.start <= newInterval.start && interval.end < newInterval.end) {
                newInterval.start = interval.start
            } else if (interval.start > newInterval.start && interval.end >= newInterval.end) {
                newInterval.end = interval.end
            }
        }
        return result
    }
}

fun main(args: Array<String>) {
    val intervals = listOf(InsertInterval.Interval(2, 6), InsertInterval.Interval(7, 9))
    val newInterval = InsertInterval.Interval(15, 18)
    val insertInterval = InsertInterval()
    for (ele in insertInterval.insert(intervals, newInterval)) {
        println(ele)
    }
}
複製程式碼

有問題隨時溝通

具體程式碼實現可以參考Github

相關文章