Merge Intervals_leetcode_go
2018-11-09 本文已影响0人
fjxCode
Merge Intervals
题目:
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
思路:
- 按interval.Start排序。有重合则合并,无重合则加到结果集。
- 注意Interval要值拷贝。
解:
func merge(intervals []Interval) []Interval {
res := make([]Interval, 0)
if len(intervals) == 0 {
return res
}
sort.Slice(intervals, func(i, j int) bool {
if intervals[i].Start < intervals[j].Start {
return true
}
return false
})
curRes := Interval{intervals[0].Start,intervals[0].End}
for i := 1; i < len(intervals); i++ {
if curRes.End >= intervals[i].Start {
if intervals[i].End > curRes.End {
curRes.End = intervals[i].End
}
} else {
res = append(res, curRes)
curRes = Interval{intervals[i].Start,intervals[i].End}
}
}
res = append(res, curRes)
return res
}