func insert(intervals [][]int, newIntervals []int) [][]int {
var res [][]int
if len(intervals) == 0 {
res = append(res, newIntervals)
return res
}
var i = 0
for i < len(intervals) && intervals[i][1] < newIntervals[0] {
res = append(res, intervals[i])
i++
}
// 这里绕。这里绕得太厉害了。
for i < len(intervals) && intervals[i][0] <= newIntervals[1] {
newIntervals[0] = min(newIntervals[0], intervals[i][0])
newIntervals[1] = max(newIntervals[1], intervals[i][1])
i++
}
res = append(res, newIntervals)
for i < len(intervals){
res = append(res, intervals[i])
i++
}
return res
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
作者:wanghao-w
链接:https://leetcode-cn.com/problems/insert-interval/solution/57insertintervalscha-ru-qu-jian-by-wanghao-w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。