给出一组区间,请合并所有重叠的区间。
请保证合并后的区间按区间起点升序排列。
思路:先对这些区间进行排序,然后遍历这些区间,判断后一个的开始点是否在前一个的结束点之前,如果是就能合并。
package main
import . "nc_tools"
import "sort"
/*
* type Interval struct {
* Start int
* End int
* }
*/
/**
*
* @param intervals Interval类一维数组
* @return Interval类一维数组
*/
func merge( intervals []*Interval ) []*Interval {
// write code here
if len(intervals) == 0 {
return intervals
}
newIntervals := Intervals(intervals)
sort.Sort(newIntervals)
var res []*Interval
res = append(res, newIntervals[0])
for i := 1; i < len(newIntervals); i++ {
num := len(res)
//如果能合并
if newIntervals[i].Start <= res[num-1].End {
if res[num-1].End < newIntervals[i].End {
res[num-1].End = newIntervals[i].End
}
} else {
res = append(res, newIntervals[i])
}
}
return res
}
type Intervals []*Interval
func (intervals Intervals) Swap(i, j int) {
tmp := intervals[i]
intervals[i] = intervals[j]
intervals[j] = tmp
}
func (intervals Intervals) Less(i, j int) bool {
if intervals[i].Start < intervals[j].Start {
return true
} else {
return false
}
}
func (intervals Intervals) Len() int {
return len(intervals)
}