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 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2019-06-17 设计模式-状态模式