【面试题】合并重叠区间

polaris · · 4016 次点击
golwei
没有永恒.
## (Interval-2.start_p) | - | -1 | 0 | 1 | | ------------- |:-------------:| -----:| -----:| |-1 | 0 | - | -| | 0 | switch-start | 0 | -| | 1 | switch-all |switch-end | -| (Interval-2.end_p)
#1
更多评论
```go func merge(intervals []Interval) []Interval { if len(intervals) <= 1 { return intervals } sort.Slice(intervals, func(i, j int) bool { return intervals[i].Start < intervals[j].Start }) res := make([]Interval, 0) swap := Interval{} for k, v := range intervals { if k == 0 { swap = v continue } if v.Start <= swap.End { swap.End = v.End } else { res = append(res, swap) swap = v } } res = append(res, swap) return res } ```
#2
```go package main import ( "fmt" ) type Section struct { Start int End int } func main() { a1 := []Section{{1, 3}, {2, 6}, {8, 10}, {15, 18}} MergeSection(a1) } func MergeSection(s1 []Section) (s2 []Section, err error) { // a2 := []Section{} // 先对结构体排序 // 判断相邻数据 for i := 0; i < len(s1); i++ { if i > 0 { if s1[i-1].End >= s1[i].Start { s1[i-1].End = s1[i].End s2 = append(s2, s1[i-1]) } else { s2 = append(s2, s1[i]) } } } fmt.Println(s2) return nil, nil } ```
#3