题解 | #合并区间#
合并区间
https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
package main import ( . "nc_tools" "sort" ) /* * type Interval struct { * Start int * End int * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param intervals Interval类一维数组 * @return Interval类一维数组 */ func max(a,b int) int{ if a>b { return a }else{ return b } } func merge( intervals []*Interval ) []*Interval { if len(intervals)==0{ return nil } sort.Slice(intervals, func(i, j int) bool{ return intervals[i].Start < intervals[j].Start }) res := make([]*Interval,0) res = append(res, intervals[0]) for i:=1;i < len(intervals);i++ { if intervals[i].Start<=res[len(res)-1].End{ res[len(res)-1].End = max(intervals[i].End,res[len(res)-1].End) }else{ res = append(res,intervals[i]) } } return res; // write code here }