u
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package top100liked
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// https://leetcode.cn/problems/merge-intervals/?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
func merge(intervals [][]int) [][]int {
|
||||
if len(intervals) <= 1 {
|
||||
return intervals
|
||||
}
|
||||
|
||||
slices.SortFunc(intervals, func(a, b []int) int {
|
||||
return cmp.Compare(a[0], b[0])
|
||||
})
|
||||
res := [][]int{}
|
||||
cur := intervals[0]
|
||||
for i := 1; i < len(intervals); i++ {
|
||||
new := intervals[i]
|
||||
// 判断是否重叠
|
||||
if cur[0] <= new[0] && new[0] <= cur[1] {
|
||||
cur = []int{cur[0], max(cur[1], new[1])}
|
||||
} else {
|
||||
res = append(res, cur)
|
||||
cur = new
|
||||
}
|
||||
}
|
||||
res = append(res, cur)
|
||||
return res
|
||||
}
|
||||
|
||||
func TestS14(t *testing.T) {
|
||||
fmt.Printf("%+v\n", merge([][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}))
|
||||
fmt.Printf("%+v\n", merge([][]int{{1, 4}, {4, 5}}))
|
||||
fmt.Printf("%+v\n", merge([][]int{{4, 7}, {1, 4}}))
|
||||
}
|
||||
Reference in New Issue
Block a user