题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
package main
import . "nc_tools"
import "sort"
/*
* type Interval struct {
* Start int
* End int
* }
*/
/**
*
* @param intervals Interval类一维数组
* @return Interval类一维数组
*/
func merge(intervals []*Interval) []*Interval {
sort.SliceStable(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})
res := make([]*Interval, 0)
for i := 0; i < len(intervals); i++ {
start, end := intervals[i].Start, intervals[i].End
for i+1 < len(intervals) && end >= intervals[i+1].Start {
if end < intervals[i+1].End {
end = intervals[i+1].End
}
i++
}
res = append(res, &Interval{
Start: start,
End: end,
})
}
return res
}