Leetcode Golang 56. Merge Intervals.go

2019-04-12 11:22:14 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412902

思路

先把起点和终点集合在一起,排序,然后再循环合并

注意处理中间不连续的情况

code

代码语言:javascript复制
func merge(intervals []Interval) []Interval {
	l := len(intervals)
	var (
		starts []int
		ends   []int
		res    []Interval
	)
	for _, v := range intervals {
		starts = append(starts, v.Start)
		ends = append(ends, v.End)
	}
	sort.Ints(starts)
	sort.Ints(ends)
	for i, j := 0, 0; i < l; i   {
		if i == l-1 || starts[i 1] > ends[i] { //中间出现了不连续,记录前一个连续值
			res = append(res, Interval{Start: starts[j], End: ends[i]})
			j = i   1
		}
	}
	return res
}

0 人点赞