牛客网: BM89
题目: 合并所有重叠子区间
思路: 按start大小排序,如果后一个start在前一个end内,则更新前一个end为后一个end及自身中的较大者,继续下一个对比合并
代码:
// go
package main
// import "fmt"
import . "nc_tools"
import "sort"
/*
* type Interval struct {
* Start int
* End int
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param intervals Interval类一维数组
* @return Interval类一维数组
*/
func max(x, y int) int {
if x > y {return x} else {return y}
}
func merge( intervals []*Interval ) []*Interval {
// write code here
if len(intervals) < 2 {
return intervals
}
sort.Slice(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})
var res []*Interval
res = append(res, intervals[0])
for i := 1; i < len(intervals); i++ {
if intervals[i].Start <= res[len(res)-1].End {
res[len(res)-1].End = max(intervals[i].End, res[len(res)-1].End)
} else {
res = append(res, intervals[i])
}
}
return res
}