讨论/《数组和字符串》 - 合并区间/
《数组和字符串》 - 合并区间

golang


type DataList [][]int

func (d DataList) Len() int           { return len(d) }
func (d DataList) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }
func (d DataList) Less(i, j int) bool { return d[i][0] < d[j][0] }

func merge(intervals [][]int) [][]int {
	data := DataList(intervals)
	result := make([][]int, 0)
	sort.Sort(data)
	result = append(result, data[0])
	length := len(result)
	for i := 1; i < len(data); i++ {
		if result[length-1][1] >= data[i][0] {
			result[length-1][1] = max(result[length-1][1], data[i][1])
		} else {
			result = append(result, data[i])
			length++
		}
	}
	return result
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
展开全部 27 讨论