Merge Intervals
2019-04-02 本文已影响0人
瞬铭
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;
}