天天看点

leetcode刷题笔记(Golang)--56. Merge Intervals

56. 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 considered overlapping.

func merge(intervals [][]int) [][]int {
	if len(intervals) <= 1 {
		return intervals
	}
	sort.Slice(intervals, func(i int, j int) bool {
		return intervals[i][0] < intervals[j][0]
	})
	res := make([][]int, 0, len(intervals))
	res = append(res, intervals[0])
	for i := 1; i < len(intervals); i++ {
		l := len(res)
		if res[l-1][1] < intervals[i][0] {
			res = append(res, intervals[i])
		} else {
			if res[l-1][1] < intervals[i][1] {
				res[l-1][1] = intervals[i][1]
			}
		}
	}
	return res    
}