57. Insert Interval

复制代码
package LeetCode_57

/**
 * 57. Insert Interval
 * https://leetcode.com/problems/insert-interval/description/
 *
 * 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]]
 * */
class Solution {
    /**
     * solution:
     * 1.insertion sort
     * 2.merge intervals
     * Time complexity:O(n), Space complexity:O(n)
     * */
    fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray>? {
        //1. find out the position to insert newInterval
        var index = 0
        val list = ArrayList<IntArray>()
        //if newInterval.start > the first one's start
        for (item in intervals) {
            if (newInterval[0] > item[0]) {
                index++
            }
        }
        for (item in intervals) {
            list.add(item)
        }
        list.add(index, newInterval)

        //2.merge intervals
        val resultList = ArrayList<IntArray>()
        for (item in list) {
            //if current start > prev.end, insert into new one
            if (resultList.isEmpty() || item[0] > resultList.get(resultList.size - 1)[1]) {
                resultList.add(item)
            } else {
                //change the end value of the last element
                resultList.get(resultList.size - 1)[1] = Math.max(resultList.get(resultList.size - 1)[1], item[1])
            }
        }
        val size = resultList.size
        val resultArray = Array(size, { IntArray(2) })
        for (i in 0 until size) {
            resultArray.set(i, resultList.get(i))
        }
        /*for (item in resultArray){
            item.forEach { print("$it,") }
        }*/
        return resultArray
    }
}
复制代码

 

posted @   johnny_zhao  阅读(186)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-06-17 设计模式-状态模式
点击右上角即可分享
微信分享提示