给定一组 区间,合并所有重叠的 区间。
例如:
> 给定:[1,3],[2,6],[8,10],[15,18]
> 返回:[1,6],[8,10],[15,18]
```go
/**
* 区间的定义如下:
* type Interval struct {
* Start int
* End int
* }
*/
func merge(intervals []Interval) []Interval {
}
```
```go
package main
import(
"fmt"
)
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< len; i++ {
if a[i].head == 0 && a[i].tail == 0{
continue
}
for j:=1 ; j < len ; j++{
if a[j].head == 0 && a[j].tail == 0 {
continue
}
if a[i].head < a[j].head && a[i].tail > a[j].tail{
a[j].head , a[j].tail = 0, 0
}else if a[i].head < a[j].head && a[i].tail < a[j].tail && a[i].tail > a[j].head{
a[i].tail = a[j].tail
a[j].head , a[j].tail = 0, 0
}else if a[i].head > a[j].head && a[i].tail > a[j].tail && a[i].head < a[j].tail{
a[i].head = a[j].tail
a[j].head , a[j].tail = 0, 0
}else if a[i].head > a[j].head && a[i].tail < 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 < len; i++{
if(a[i].head == 0 && 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) <= 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