https://leetcode.com/problems/merge-intervals/
合并区间,当数组之间存在交集的时候,讲数组合并。(这里的数组类都定义好了,就是两个int的区间)
/**
* Definition for an interval.
* class Interval {
* public $start = 0;
* public $end = 0;
* function __construct(int $start = 0, int $end = 0) {
* $this->start = $start;
* $this->end = $end;
* }
* }
*/
/**
* @param Interval[] $intervals
* @return Interval[]
*/
function merge($intervals) {
if(!$intervals){
return [];
}
usort($intervals,function($intervalsa,$intervalsb){
return $intervalsa->start <= $intervalsb->start ? -1 : 1;
});
$res[] = $intervals[0];
for($i = 1; $i<count($intervals);$i++){
if($res[count($res) - 1]->end < $intervals[$i]->start){
$res[] = $intervals[$i];
}else{
$res[count($res) - 1]->end = max($res[count($res) - 1]->end,$intervals[$i]->end);
}
}
return $res;
}
网友评论