以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
提示:
- 1 <= intervals.length <= 104
- intervals[i].length == 2
- 0 <= starti <= endi <= 104
解题:
func merge(intervals [][]int) [][]int {
l := len(intervals)
for i := 0; i < l-1; i++ {
min := intervals[i][0]
minIndex := i
for j := i; j < l; j++ {
if intervals[j][0] < min {
min = intervals[j][0]
minIndex = j
}
}
intervals[i], intervals[minIndex] = intervals[minIndex], intervals[i]
}
for i := 1; i < l; i++ {
if intervals[i-1][0] > intervals[i][0] {
intervals[i-1], intervals[i] = intervals[i], intervals[i-1]
}
}
var r [][]int
for i := 1; i < l; i++ {
if intervals[i][0] <= intervals[i-1][1] {
intervals[i][0] = intervals[i-1][0]
if intervals[i-1][1] > intervals[i][1] {
intervals[i][1] = intervals[i-1][1]
}
} else {
r = append(r, intervals[i-1])
}
}
r = append(r, intervals[l-1])
return r
}
官方解答:
func merge(intervals [][]int) [][]int {
if len(intervals) == 0 {
return [][]int{}
}
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
var merged [][]int
for i := 0; i < len(intervals); i++ {
l, r := intervals[i][0], intervals[i][1]
if len(merged) == 0 || merged[len(merged)-1][1] < l {
merged = append(merged, intervals[i])
} else {
merged[len(merged)-1][1] = max(merged[len(merged)-1][1], r)
}
}
return merged
}
func max(x, y int) int {
if x > y {
return x
}
return y
}