排序,然后逐一合并
时间复杂度: O(NlogN)
空间复杂的: O(logN)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| func merge(intervals [][]int) [][]int { sort.Slice(intervals, func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] < intervals[j][1] } else { return intervals[i][0] < intervals[j][0] } })
ans := [][]int{} l, r := intervals[0][0], intervals[0][1]
for i := 1; i < len(intervals); i++ { if intervals[i][0] <= r { if (intervals[i][1] > r) { r = intervals[i][1] } continue }
ans = append(ans, []int{l, r}) l = intervals[i][0] r = intervals[i][1] }
ans = append(ans, []int{l, r}) return ans }
|