《leetcode-go》合并区间

本文介绍了一种算法,用于合并输入的一维区间数组,确保合并后的区间按起始点升序排列,并消除重叠部分。通过排序和遍历操作,实现区间合并。

给出一组区间,请合并所有重叠的区间。

请保证合并后的区间按区间起点升序排列。

思路:先对这些区间进行排序,然后遍历这些区间,判断后一个的开始点是否在前一个的结束点之前,如果是就能合并。

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)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值