# 【面试题】合并重叠区间

polaris · · 3539 次点击
```go package main import( &#34;fmt&#34; ) type SECTION struct{ head int tail int } func main(){ a := []SECTION{{1,3},{2,6},{8,10},{15,18}, {9, 20}} fmt.Println(Section(a)) } func Section(a []SECTION) []SECTION{ ret := []SECTION{} len := len(a) for i:=0 ; i&lt; len; i++ { if a[i].head == 0 &amp;&amp; a[i].tail == 0{ continue } for j:=1 ; j &lt; len ; j++{ if a[j].head == 0 &amp;&amp; a[j].tail == 0 { continue } if a[i].head &lt; a[j].head &amp;&amp; a[i].tail &gt; a[j].tail{ a[j].head , a[j].tail = 0, 0 }else if a[i].head &lt; a[j].head &amp;&amp; a[i].tail &lt; a[j].tail &amp;&amp; a[i].tail &gt; a[j].head{ a[i].tail = a[j].tail a[j].head , a[j].tail = 0, 0 }else if a[i].head &gt; a[j].head &amp;&amp; a[i].tail &gt; a[j].tail &amp;&amp; a[i].head &lt; a[j].tail{ a[i].head = a[j].tail a[j].head , a[j].tail = 0, 0 }else if a[i].head &gt; a[j].head &amp;&amp; a[i].tail &lt; a[j].tail{ a[i].head, a[i].tail = a[j].head, a[j].tail a[j].head , a[j].tail = 0, 0 } } } for i := 0; i &lt; len; i++{ if(a[i].head == 0 &amp;&amp; a[i].tail == 0){ continue; } ret = append(ret, a[i]) } return ret } ```
#4

## (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) &lt;= 1 { return intervals } sort.Slice(intervals, func(i, j int) bool { return intervals[i].Start &lt; intervals[j].Start }) res := make([]Interval, 0) swap := Interval{} for k, v := range intervals { if k == 0 { swap = v continue } if v.Start &lt;= swap.End { swap.End = v.End } else { res = append(res, swap) swap = v } } res = append(res, swap) return res } ```
#2